1

I am trying to graph a Blackbody's radiated power per unit energy range. My code is the following:

import numpy as np
import math
import matplotlib.pyplot as plt 

h = 6.626*(10**(-34))
c = 3*(10**8)
k = 1.38*(10**(-23))
T = 1000

x = np.array(range(100))
y = (x**3)/((math.exp(x/(k*T)))-1)

# Create the plot
plt.plot(x,y)

# Show the plot
plt.show()

And I get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-86ad11932249> in <module>
      9 
     10 x = np.array(range(100))
---> 11 y = (x**3)/((math.exp(x/(k*T)))-1)
     12 
     13 # Create the plot

TypeError: only size-1 arrays can be converted to Python scalars

Could someone explain why what I have is wrong?

  • 1
    `math.exp` calculates exponent of single variable and `np.exp` calculates it for every item of array. You need to operate on arrays – mathfux Nov 04 '20 at 00:02
  • Does this answer your question? [TypeError: only length-1 arrays can be converted to Python scalars while plot showing](https://stackoverflow.com/questions/36680402/typeerror-only-length-1-arrays-can-be-converted-to-python-scalars-while-plot-sh) – AMC Nov 04 '20 at 00:08

2 Answers2

2

It is because math.exp() requires a scalar variable, but array enters in your code. In addition, I think you are not familiar with numpy. Try this code.

import numpy as np
import math
import matplotlib.pyplot as plt 

h = 6.626*(10**(-34))
c = 3*(10**8)
k = 1.38*(10**(-23))
T = 1000

x = np.arange(100) # np.arange is more efficient
y = (x**3) / (np.exp(x/(k*T))-1)

# Create the plot
plt.plot(x,y)

# Show the plot
plt.show()

Note that K * T is so small, (np.exp(x/(k*T))-1) returns array including infinity.

Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11
0

You can replace math with np. However, you might want to rewrite your equation as the denominator returns inf all of the time (except for x[0]=0).

saedx1
  • 984
  • 6
  • 20