类型错误:无法将表达式转换为浮点数 [英] TypeError: can't convert expression to float
问题描述
I am a python newbie. I am trying to evaluate Planck equation using python. I have written a simple program. But when I give input to it is giving me an error. can anyone hep me where I am going wrong? Here is the program and the error:
Program:
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()
Input: I have imported the function as 'cp' and the input is as follows
value = (cp.planck_law(400,2000))
Error:
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
It seem like you are mixing namespaces, since your are using from ... import *
. You wanted to use sympy.exp()
but your code uses math.exp()
. It is good practice to keep the namespaces separated, i.e. never use from ... import *
- it might seem like more typing at first, but will produce much cleaner easier comprehensible code in the end.
Try:
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)
这篇关于类型错误:无法将表达式转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!