TypeError:无法将表达式转换为浮点型 [英] TypeError: can't convert expression to float

查看:349
本文介绍了TypeError:无法将表达式转换为浮点型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python新手.我正在尝试使用python评估Planck方程.我写了一个简单的程序.但是,当我输入信息时,会给我一个错误.谁能帮助我解决我的问题?这是程序和错误:

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:

程序:

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",输入如下:

Input: I have imported the function as 'cp' and the input is as follows

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().良好的做法是将名称空间保持分隔,即从不使用from ... import *-乍一看似乎要键入更多内容,但最终会产生更清晰,更容易理解的代码. 试试:

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)

这篇关于TypeError:无法将表达式转换为浮点型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆