我必须在Python中为我正在做的项目制作拉格朗日多项式.我正在做一个重心的样式,以避免使用显式的for循环而不是Newton的分割差异样式.我遇到的问题是我需要将除法除以零,但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 …Run Code Online (Sandbox Code Playgroud)