我是一个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
解决方法:
看起来你正在混合命名空间,因为你使用的是…… import *.您想使用sympy.exp(),但您的代码使用math.exp().保持名称空间分离是好的做法,即永远不要使用… 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)