Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 801
Niroop Avatar asked Mar 22 '26 17:03

Niroop


1 Answers

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)
like image 119
Dietrich Avatar answered Mar 24 '26 07:03

Dietrich