类型错误:无法将表达式转换为浮点数

3 投票
3 回答
43740 浏览
提问于 2025-04-17 23:16

我是一名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

3 个回答

1

当你调用你的函数时,需要给温度和波长的参数传入单位。比如调用 cp.planck_law(400*meters,2000*K) 就会得到预期的结果 1.15133857387385e-33*kg/(m*s)

问题出在指数函数上,它需要接收一个没有单位的参数。因为你传入的参数没有包含单位,所以Sympy把它们当成了没有单位的浮点数,而不是需要的温度和长度。

1

你提到的这个公式 h*f/(k*T) 不是无单位的,所以你不能把它传给 exp() 函数。在物理上,这样做也没有意义 ;-)

如果你把它除以 Km,你可以得到一个结果:

exp(h*f/(k*T)/K/m)

但这样做肯定没有意义。这样做只是为了让程序运行(结果却是无意义的)。

我想你需要检查一下你的公式,弄清楚你到底想怎么计算要传给 exp() 的值。

编辑:

正如Pascal指出的,你只是缺少了传入参数的单位。试试这个:

planck_law(400e-9*m,2000*K)

返回:

3.20224927538564e-22*kg/(m*s)
10

看起来你在混淆命名空间,因为你使用了 from ... import *。你想用的是 sympy.exp(),但你的代码却用了 math.exp()。保持命名空间的分离是个好习惯,也就是说,尽量不要使用 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)

撰写回答