"RuntimeWarning: overflow encountered in exp", but not when using an array

Question:

I am implementing the following formula:

survival function, eq. 49 from doi: 10.1063/1.447954

in Python (with SciPy and NumPy). I wrote the following expression:

def fokker_plank_solution_1_sur(t, k, c, x_0):
    if k == 0 & c == 0:
        pass
    
    else:
        print("Case 2")
        t_1 = (k - c)/(k - 2*c)
        t_2 = np.exp((k * x_0 + k*(k - 2*c)*t))
        t_3 = erfc((x_0 + 2 * (k - c) * t)/(np.sqrt(4*t)))
        t_4 = 0.5
        t_5 = erfc((- x_0 + 2 * c * t)/np.sqrt(4 * t))
        t_6 = k/(k - (2 * c))
        t_7 = np.exp(2 * c * x_0)
        t_8 = erfc((x_0 + 2*c*t)/(np.sqrt(4*t)))
        
        y = t_1 * t_2 * t_3 + t_4 * (t_5 - t_6 * t_7 * t_8)
        
        return y

Case 1:
If I am using the following conditions, I am getting "good" numbers (t_2 = 1.94e+05) and the plotmatplotlib of the survivalrate

D = .25
x_val = np.linspace(1,500,250)
c = 0
x_0 = 5

for k in [.8]:
    y_val = fokker_plank_solution_1_sur(x_val * D, k, c, x_0)
                                                   |      |

    # print(np.concatenate((x_val.reshape([250,1]), y_val.reshape([250,1])), axis = 1))
    
    plt.plot(x_val, y_val)

Case 2:
However, if I am just putting this in the console,

fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8)
                                                     |       |

I get the return

t_2 = np.exp((k * x_0 + k*(k - 2*c)*t))

RuntimeWarning: overflow encountered in exp

After some search, I found t_2 is just getting too big, to be further processed (1,2), t_2 is then

e^1258.0

-> So the question now is, why can python calculate numbers, when using a NumPy array indirectly (case 1), but not when using the NumPy array directly (case 2)?
Thank you for reading this far.

Asked By: eB_Bo

||

Answers:

It depends on how you tell NumPy to handle errors. You can control it with seterr or errstate.

For example:

>>> with np.errstate(all='ignore'):
...    print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))
nan


>>> with np.errstate(all='warn'):
...     print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))

RuntimeWarning: overflow encountered in exp
  t_2 = np.exp((k * x_0 + k * (k - 2 * c) * t))
RuntimeWarning: invalid value encountered in double_scalars
  y = t_1 * t_2 * t_3 + t_4 * (t_5 - t_6 * t_7 * t_8)
nan


>>> with np.errstate(all='raise'):
...     print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))
Error
Traceback (most recent call last):
  [...]
  t_2 = np.exp((k * x_0 + k * (k - 2 * c) * t))
FloatingPointError: overflow encountered in exp

You are likely using a different setting in your program and when you call the function from the console.

Answered By: aerobiomat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.