Plotting Idealized Blackbody Spectra

天涯浪子 提交于 2020-06-01 06:44:46

问题


So I am getting a couple errors

RuntimeWarning: overflow encountered in exp
intensity = a/ ( (wav**5) * (np.exp(b) - 1.0) )

and

RuntimeWarning: invalid value encountered in multiply
intensity = a/ ( (wav**5) * (np.exp(b) - 1.0) )

Even with these errors (and one more about dividing by zero that I ignore lol) my graph gets produced correctly either way. I am just wondering if anyone can help me clear up these errors? Please and thanks.

Here is the full code:

import numpy as np
import matplotlib.pyplot as plt
from astropy import constants as const


def planck(T, wav):
    a = 2.0*h*c**2
    b = h*c/(wav*k*T)
    intensity = a/ ( (wav**5) * (np.exp(b) - 1.0) )
    return intensity

# Part 1: Plotting Planck's Law

T1 = 3750
T2 = 5200
T3 = 9600 # Temperature of M0 star, the Sun, and A0 star (K)
c = const.c.value
h = const.h.value
k = const.k_B.value
l = np.linspace(0, 1.5e-6, 1500) #Array of wavlengths (meters)
IM0 = planck(T1, l) 
Isun = planck(T2, l)
IA0 = planck(T3, l) # Planck's law intensities 

plt.figure(1) # Plot of the three idealized blackbody spectra
plt.plot(l, IM0, 'k-', label = 'M0 Star')
plt.plot(l, Isun, 'r--', label = 'Sun')
plt.plot(l, IA0, 'b-.', label = 'B0')
plt.xlabel('Wavelength (meters)')
plt.ylabel('Intensity (W sr^{-1} m^{-3})')
plt.title('Idealized Blackbody Spectra')
#plt.legend('M0 Star', 'Sun', 'B0 Star')
leg = plt.legend()
plt.ticklabel_format(axis="x", style="sci", scilimits=(0,0)) # Scientific not

回答1:


First 5 values of l are too small, which causes high values of b and thus a numerical overflow in exp (as exp(1500) is just a very large number).

In fact, the first value in l is simply zero, and thus wav in planck() becomes infinite and 1/wav**5 is NaN.

Hence all the warnings. Set l = np.linspace(6e-9, 1.5e-6, 1500) and you'll be fine.

And no, index, it is not IDE warning, it's Python warning. There are ways to suppress such warnings, but you can only do that once you know exactly what are you suppressing and why.




回答2:


Since your code runs, just ignore the RuntimeWarning because it's just a warning that doesn't effect your code or anything. Your IDE is just warning you. I think if you try in a different IDE, there will be no warning. But i could be wrong



来源:https://stackoverflow.com/questions/61494564/plotting-idealized-blackbody-spectra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!