I'm using a while loop to obtain a backwards decay curve for a radioactive element.
import numpy as np
import csv
lmbd=np.log(2)/12.43
year=list(range(-48050,2012))
f=0
decay=[]
decay.append(0.45) # concentration of sample during year of sampling
while f<len(year): # Creating the backwards decay curve sample
p=decay[f]
x=p/np.exp(-lmbd)
decay.append(x)
f=f+1
print(decay)
When I run the above code I get the following error:
Traceback (most recent call last): File "", line 13, in
x=p/np.exp(-lmbd)
File "C:\Python32\lib\idlelib\PyShell.py", line 59, in idle_showwarning file.write(warnings.formatwarning(message, category, filename,
AttributeError: 'NoneType' object has no attribute 'write'
However, if I substitute len(year)
with, for example, 50
then the loop runs smoothly. If I substitute len(year)
with 50062
(the value of len(year)
) I still get the error.
lmbd
value so values don't get so large)I'm using Python 3.2
Thanks to PaF, User, and eryksun for providing the answers (in the comments) :
I was getting the wrong warning (in IDLE) in regards to the script.
If I ran the script in cmd
(as per User suggestions) I got the RuntimeWarning: overflow encountered in double_scalars x=p/np.exp(-lmbd)
error.
Also if I added import sys, idlelib.PyShell; idlelib.PyShell.warning_stream = sys.stderr
to the script (as per eruksun suggestion) I also get the correct error in IDLE (which I was using).
The script can now run to completion but the decay list has a whole lot of inf
values at the end which is dealt with in the next point.
To deal with the overflow
problem:
I tried replacing the while
statement with while f<len(year) and decay[-1] != np.inf:
(as per PaF suggestion). The loop stops once the last value in the decay
list reaches inf
; however, it attaches a single inf
value to the end of the list. Additionally, the overflow
error remains.
I instead added an if
statement within the loop to exit once inf
is reached but before appending to the list (however, the overflow
error still comes up but produces a list without any inf
values in it)
The updated script, which works, is:
import numpy as np
import csv
import sys, idlelib.PyShell; idlelib.PyShell.warning_stream = sys.stderr
lmbd=np.log(2)/12.43
year=list(range(-48050,2012))
f=0
decay=[]
decay.append(0.45)# concentration of sample during year of sampling
while f<len(year): # Creating the backwards decay equation for each sample
p=decay[f]
x=p/np.exp(-lmbd)
if x==np.inf:
break
decay.append(x)
f=f+1
print(decay)
print("end")
While this still gives the overflow
error in both IDLE and CMD, I think that is OK for my purposes as I'm not worried about the extremely large numbers and the script runs to completion.