如何创建除"RuntimeWarning: invalid value encountered in double_scalars"?



我正在进行数值推导,并在python中实验Δx的值有多小。我知道使用np.linspace(0, 1, 1000)会创建四舍五入为0的值。为了防止我原本干净的输出窗口显示错误消息,我尝试了以下方法:

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

但当我运行时,我仍然会收到以下消息:

RuntimeWarning: invalid value encountered in double_scalars

那么,除了那个确切的警告,我还有别的办法吗?我也尝试过删除整个警告文本(比如从Runtime到_scalars(,但都不起作用。

这是我的程序

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()

如果这行得通,那是因为我把它翻译成了英语。

您将ΔxValues定义为np.linspace(0, 1, 1000)。问题是在中

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

你除以ΔxΔxValues中的第一个数字是0,这显然会导致除以0的错误。

print(ΔxValues[0])
# 0.0

通过重新定义ΔxValues或简单地使用ΔxValues[1:]来避免这种情况

要将try/except中的警告当作错误来捕获,可以使用警告模块中的filterwarnings。

import warnings
warnings.filterwarnings("error")

相关内容

最新更新