RuntimeWarning: invalid value encountered in double_scalars app.launch_new_instance()

后端 未结 1 1550
终归单人心
终归单人心 2021-01-12 08:11

I am applying Euler\'s method to solve a differential equation. This is my code:

def f(x, y):
    return ((x**(2))*y)/((x**(4)) + (y**(4)))

di = 0.01
I = 1         


        
相关标签:
1条回答
  • 2021-01-12 08:33

    Your code is running into Divide by Zero Error. Try this to convince yourself:

    >>> def f(x, y):
    ...     return ((x**(2))*y)/((x**(4))+(y**(4)))
    ...
    >>> I, di = 100, 0.01
    >>> x = np.linspace(-I, I, int(I/di) + 1)
    >>> w = np.zeros(len(x))
    >>> i = len(x)//2 + 1
    >>> i
    5001
    >>> f(x[i-1], w[i-1])
    nan
    

    It clearly emerges from the interactive session above that when i takes the value 5001 in the for loop, f(x[i-1], w[i-1]) yields nan. There are several solutions to this issue. For instance, in order to avoid NaN values you could check whether the denominator of the fraction returned by f() is zero prior to perform the division. If it is, you should return a conventional value of your choice (for example 0) instead of the result of the division. The following snippet implements such approach though a conditional expression:

    def f(x, y):
        return (0 if x==0 and y==0 else float(x**2*y)/(x**4 + y**4))
    

    Alternatively, you could disable run time warnings (but if you do so you need to be aware of the potential risks) by including this code in your script:

    import warnings
    
    def f(x, y):
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')        
            return ((x**(2))*y)/((x**(4)) + (y**(4)))
    

    The proposed workarounds avoid the RuntimeWarning but don't get your code working as you expect. Indeed, the calculated solution w is a vector in which all the elements are zero. I guess the reason for your code not being working properly is that you missed to assign w[0] an initial value different to 0.

    For example, if you simply add this line just before the for loop:

    w[0] = 0.5
    

    you get this (apparently meaningful) curve rather than a flat plot.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题