Search code examples
pythonnumpyerror-handlingtry-exceptdivide-by-zero

How could I create an except for "RuntimeWarning: invalid value encountered in double_scalars"?


I am working on numeric derivation, and experiment with how small of a value Δx can be in python. I have understood that using np.linspace(0, 1, 1000) creates values that are rounded to 0. To prevent my otherwise clean output window from showing error messages, I have tried this:

try:
    #do the numeric derivation
except RuntimeWarning:
    #do something else
else:
    #the actual function of the program

But when I run I still get the following message:

RuntimeWarning: invalid value encountered in double_scalars

So, is there a way for me to except that exact warning? I have also tried to except the entire warning text (like, from Runtime to _scalars), but nothing works.

Here is my program

import numpy as np
import matplotlib.pyplot as plt

xValue = np.linspace(0, 5, 5)
ΔxValues = np.linspace(0, 1, 1000)

def f(x):
    return x**2 + 2*x + 4
def fDerN(x, Δx):
    return (f(x + Δx) - f(x))/Δx
def fDerA(x):
    return 2*x + 2

difference1, difference2, difference3, difference4, difference5= [], [], [], [], []

for Δx in ΔxValues:
    try:
        fDerN(1, Δx)
        fDerN(2, Δx)
        fDerN(3, Δx)
        fDerN(4, Δx)
        fDerN(5, Δx)
    except RuntimeWarning:
        hasBeenWarning = True #Just to have an indented piece of code
    else:
        difference1.append(abs(fDerN(1, Δx) - fDerA(1)))
        difference2.append(abs(fDerN(2, Δx) - fDerA(2)))
        difference3.append(abs(fDerN(3, Δx) - fDerA(3)))
        difference4.append(abs(fDerN(4, Δx) - fDerA(4)))
        difference5.append(abs(fDerN(5, Δx) - fDerA(5)))

plt.plot(ΔxValues, difference1, label="x = 1")
plt.plot(ΔxValues, difference2, label="x = 2")
plt.plot(ΔxValues, difference3, label="x = 3")
plt.plot(ΔxValues, difference4, label="x = 4")
plt.plot(ΔxValues, difference5, label="x = 5")

plt.title("Difference between numeric and algebraic derivation for different values of x og Δx")
plt.grid()
plt.legend()

plt.show()

If this works, it is because I translated it to english.


Solution

  • You define ΔxValues as np.linspace(0, 1, 1000). The problem is that in

    def fDerN(x, Δx):
        return (f(x + Δx) - f(x))/Δx
    

    you divide by Δx. The first number in ΔxValues is 0, which will obviously cause a division by 0 error.

    print(ΔxValues[0])
    # 0.0
    

    Circumvent this by redefining ΔxValues, or by simply using ΔxValues[1:]

    To catch the warning in your try/except as if it were an error, you can use filterwarnings from the warnings module.

    import warnings
    warnings.filterwarnings("error")