Skip to main content
 首页 » 编程设计

python之类型错误 : can't convert expression to float

2025年05月04日13grandyang

我是一个python新手。我正在尝试使用 python 评估普朗克方程。我写了一个简单的程序。但是当我输入它时,它给了我一个错误。谁能帮助我哪里出错了?这是程序和错误:

程序:

from __future__ import division 
from sympy.physics.units import * 
from math import * 
import numpy 
from scipy.interpolate import interp1d 
 
#Planck's Law evaluation at a single wavelength and temperature 
def planck_law(wavelength,temperature): 
    T=temperature 
    f=c/wavelength 
    h=planck 
    k=boltzmann 
    U=2*h/(c**3)*(f**3)/(exp(h*f/(k*T))-1) 
    return U.evalf() 

输入: 我已将函数导入为“cp”,输入如下

value = (cp.planck_law(400,2000)) 

错误:

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module>`enter code here` 
  File "Camera_performance.py", line 14, in planck_law 
  U=2*h/(c**3)*(f**3)/(exp(h*f/(k*T))-1) 
  File "/usr/lib/python2.7/dist-packages/sympy/core/expr.py", line 221, in __float__ 
  raise TypeError("can't convert expression to float") 
 
TypeError: can't convert expression to float 

请您参考如下方法:

您似乎在混合命名空间,因为您使用的是 from ... import *。您想要使用 sympy.exp(),但您的代码使用了 math.exp()。保持 namespace 分离是一种很好的做法,即永远不要使用 from ... import * - 一开始看起来需要更多的输入,但最终会产生更清晰、更容易理解的代码。 尝试:

import sympy as sy 
import sympy.physics.units as units 
 
def planck_law(wavelength,temperature): 
     """Planck's Law evaluation at a single wavelength and temperature """    
     T=temperature 
     f=units.c/wavelength 
     h=units.planck 
     k=units.boltzmann 
     U=2*h/(units.c**3)*(f**3)/(sy.exp(h*f/(k*T))-1) 
     return U.evalf() 
 
# Test: 
print(planck_law(640e-9*units.m, 500*units.K)) 
# Result: 1.503553603007e-34*kg/(m*s)