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

标签 python python-2.7 numpy scipy sympy

我是一个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)

关于python - 类型错误 : can't convert expression to float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22555056/

相关文章:

python - Pandas :如何检查另一列特定值之后是否有一系列正值

Python - 将函数调用拆分为函数和参数

python - 在 Django 中获取对另一个应用程序中模型的引用

python - 有一个 numpy.dot 文档示例不清楚,具有高维点积

python - Selenium Web 驱动程序使用 POST 请求导航到页面

python - 在模块函数调用之间存储状态

python - 枚举可以用在递归中吗?这个例子的递归是什么?

python - 错误: can only concatenate list (not "int") to list

python - 使用不同的步骤创建 numpy 数组

python - 如何有效地改变数组中一定数量的值?