Reputation: 11
I want to plot the graphs for different temperatures and frequencies in Python, I defined a function, but when I want to plot it, it shows me an error.
def planck(v,T):
h=6.62606957*(10**-34.0)
c=3*(10**8.0)
k=1.3806488*(10**-23.0)
x=(h*8*pi/c**3.0)
y=v**3
exponente = (h*v/k*T)
ex = math.exp(exponente)-1
PLANCK=(x*y)*(ex**-1)
return PLANCK
x0, xf, dx = 800,2*(10**8),1000
X = arange(x0, xf, dx)
print X
P1=planck(X, 3000)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-034ad82af010> in <module>()
----> 1 P1=planck(X, 3000)
<ipython-input-11-e52b9512e92c> in planck(v, T)
7 y=v**3
8 exponente = (h*v/k*T)
----> 9 ex = math.exp(exponente)-1
10
11 PLANCK=(x*y)*(ex**-1)
TypeError: only length-1 arrays can be converted to Python scalars
And then, if I just use exp
instead of math.exp
, the graph results a constant.
Upvotes: 1
Views: 2623
Reputation: 22659
@Sven Marnach got the programming bit right, you need to use Numpy exp
.
As for why you get the constants, you've written your function using SI units. As a result, your input must be in SI units.
You want to divide X
by 1e9
if your wavelengths were in nanometers. As it stands, you are passing wavelengths of ~800 meters.
Upvotes: 0
Reputation: 62
Compute the constant values once, then hard-code them, if you need some speed...
Upvotes: -1
Reputation: 880707
In addition to using numpy.exp
instead of math.exp
, you also need to specify the dtype of X
to be float
rather than int32
. With int32
, the largest number representable is
In [46]: np.iinfo('int32').max
Out[46]: 2147483647
and y=v**3
exceeds this value:
In [38]: v
Out[38]:
array([ 800, 1800, 2800, ..., 199997800, 199998800,
199999800])
In [37]: y
Out[37]:
array([ 512000000, -2147483648, -2147483648, ..., -2147483648,
-2147483648, -2147483648])
Thus the reason why your values look like constants is because of arithmetic overflow.
So change
X = np.arange(x0, xf, dx)
to
X = np.arange(x0, xf, dx, dtype='float')
import matplotlib.pyplot as plt
import numpy as np
pi = np.pi
def planck(v,T):
h=6.62606957*(10**-34.0)
c=3*(10**8.0)
k=1.3806488*(10**-23.0)
x=(h*8*pi/c**3.0)
y=v**3
exponente = (h*v/k*T)
ex = np.exp(exponente)-1
PLANCK=(x*y)*(ex**-1)
return PLANCK
x0, xf, dx = 800,2*(10**8),1000
X = np.arange(x0, xf, dx, dtype='float')
P1 = planck(X, 3000)
plt.plot(X, P1)
plt.show()
Upvotes: 6