我必须在Python中创建一个拉格朗日多项式,用于我正在做的项目。我正在做一个重心风格的循环,以避免使用显式的for循环,而不是牛顿的除差风格的循环。我遇到的问题是,我需要捕获一个被零除的结果,但是Python (或者numpy)只是把它变成了一个警告,而不是一个正常的异常。
因此,我需要知道如何捕捉这个警告,就像它是一个异常一样。我在这个网站上发现的与此相关的问题没有以我需要的方式得到回答。下面是我的代码:
import numpy as np
import matplotlib.pyplot as plt
import warnings
class Lagrange:
def __init__(self, xPts, yPts):
self.xPts = np.array(xPts)
self.yPts = np.array(yPts)
self.degree = len(xPts)-1
self.weights = np.array([np.product([x_j - x_i for x_j in xPts if x_j != x_i]) for x_i in xPts])
def __call__(self, x):
warnings.filterwarnings("error")
try:
bigNumerator = np.product(x - self.xPts)
numerators = np.array([bigNumerator/(x - x_j) for x_j in self.xPts])
return sum(numerators/self.weights*self.yPts)
except Exception, e: # Catch division by 0. Only possible in 'numerators' array
return yPts[np.where(xPts == x)[0][0]]
L = Lagrange([-1,0,1],[1,0,1]) # Creates quadratic poly L(x) = x^2
L(1) # This should catch an error, then return 1.
当执行这段代码时,我得到的输出是:
Warning: divide by zero encountered in int_scalars
这就是我想要捕捉到的警告。它应该发生在列表理解内部。
发布于 2016-04-08 07:40:21
为了详细说明@Bakuriu上面的答案,我发现这使我能够以类似于捕获错误警告的方式捕获运行时警告,并很好地打印出警告:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
answer = 1 / 0
except Warning as e:
print('error found:', e)
您可能会尝试放置warnings.catch_warnings(),这取决于您希望以这种方式使用捕获错误的保护伞有多大。
发布于 2017-12-20 12:46:30
删除warnings.filterwarnings并添加:
numpy.seterr(all='raise')
https://stackoverflow.com/questions/15933741
复制相似问题