Search code examples
pythonnumpytypessqrt

RuntimeWarning: invalid value encountered in double_scalars related to np.sqrt


I have defined a mathematical function with np.sqrt(a positive number) in it. It returns me RuntimeWarning.

After I simplify it to a very simple mathematical function that anyone can solve manually, it still return me the error. Below is the simplified function:

import numpy as np
n=30
def f0(x,k):
    bot = 9.37 * 10**(-4) * k**(0.25)
    x_0 = 2*bot
    #print(x_0)
    E_c = 4730 * np.sqrt(k)
    #print(E_c)
    r = E_c/(E_c - k/bot)
    #print(r)
    top = x/(1+(x/x_0)**n)**(1/n) 

    return (top/bot)**r

a = f0(-0.001,36)

It returns:

RuntimeWarning: invalid value encountered in double_scalars

And a is nan

It works well if the input x >= 0, or I remove np.sqrt() to the result of the square root of the number inside the np.sqrt().

What's reason of that.

I have noticed the type of np.sqrt is a bit different to another number. Is this the reason?


Solution

  • Your issue is not with the numpy square root. The value you are trying to return to a, involves raising a negative number to a non-integer power. This is mathematically undefined.

    The mathematical operation, although I am quite sure python uses a different numerical approximation, is:

    x = 5
    r = 1.234
    x**r # 7.2866680501380845
    import math
    math.exp(r*math.log(x)) # 7.286668050138084
    

    Now imagine what happens if r is negative: you try to take the natural logarithm of a negative number. This will result in a NaN. Depending on the function used, you will be presented with a range of errors.

    The solution is to enforce the quantity top/bot to be positive.