1

I am a beginner to Python. I have written a function which calculates numbers that are of the order 10^-15.

While generating the output of the code, an error says "Numerical result out of range". What are possible reasons for which this error occurs?

Here is my code.

import numpy as np
import matplotlib.pyplot as plt
T=4.32*10**19
i=input("Number of iterations ")
h=T/i
a=[0.01]*6000
t=[0.0]*6000
data = np.loadtxt('/home/user/t.txt')
t=data[:]
def f (a):
    if a!=0:    
        c=((0.75/a + 0.044/(a**2) + 0.74*(a**2))**0.5)  
        return c
    else :
        return 0

for n in range(0,5998):
    k1=f ( a[n] );
    k2=f ( a[n]+(h/2)*k1 );
    k3=f ( a[n]+(h/2)*k2 );
    k4=f ( a[n]+h*k3 ); 
    a[n+1]=(a[n]+(h/6)*(k1 + 2*k2 + 2*k3 + k4))

fo=open("a_of_t.txt", "w")
for item in a:
    fo.write("%e\n" % item)
fo.close()

plt.plot(t,a, 'k')
plt.show()

The error reads

line 23, in <module>
    k3=f ( a[n]+(h/2)*k2 );
line 15, in f
    c=((0.75/a + 0.044/(a**2) + 0.74*(a**2))**0.5)  
OverflowError: (34, 'Numerical result out of range')
user40330
  • 111
  • 1
  • 6

1 Answers1

0

Python decimals are stored as 64-bit floats, and as such, have finite precision. 10^-15 cannot be represented using a float. Consider using the decimal module.

James
  • 1,198
  • 8
  • 14
  • 2
    Python uses double (64-bit floats) which have a magnitude range of roughly 1e308 to 1e-308, plenty good enough for the OP's stated range of 1e-15. – wallyk Jun 30 '15 at 22:39
  • @James Can you suggest me how to incorporate decimal module in this code? I am not getting it. – user40330 Jun 30 '15 at 23:09
  • @user40330 just convert all your variables to `Decimal` by doing `Decimal(var)`. For example, `T=Decimal(4.32*10**19)`, `i=Decimal(input("Number of iterations "))`. If you want a `float` at the end, just cast using `float(someDecimal)`. – James Jun 30 '15 at 23:36
  • @James Thanks! that helped – user40330 Jul 01 '15 at 11:14