【问题标题】:How could I create an except for "RuntimeWarning: invalid value encountered in double_scalars"?我如何创建一个“RuntimeWarning:double_scalars 中遇到的无效值”除外?
【发布时间】:2021-11-24 09:34:22
【问题描述】:

我正在研究数值推导,并尝试在 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()

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

【问题讨论】:

  • 你能发布一个可重现的例子吗?
  • @MitchellOlislagers 现在我将其添加到问题中
  • np.warnings.filterwarnings 可用于将特定警告更改为错误。
  • 好的,它是如何工作的?

标签: python numpy error-handling try-except divide-by-zero


【解决方案1】:

您将Δ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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多