我想用拉格朗日方法对多项式进行插值,但这段代码不起作用:
def interpolate(x_values, y_values):
def _basis(j):
p = [(x - x_values[m])/(x_values[j] - x_values[m]) for m in xrange(k + 1) if m != j]
return reduce(operator.mul, p)
assert len(x_values) != 0 and (len(x_values) == len(y_values)), 'x and y cannot be empty and must have the same length'
k = len(x_values)
return sum(_basis(j) for j in xrange(k))
我关注了Wikipedia ,但是当我运行它时,我在第 3 行收到了一个 IndexError!
谢谢
最佳答案
尝试
def interpolate(x, x_values, y_values):
def _basis(j):
p = [(x - x_values[m])/(x_values[j] - x_values[m]) for m in xrange(k) if m != j]
return reduce(operator.mul, p)
assert len(x_values) != 0 and (len(x_values) == len(y_values)), 'x and y cannot be empty and must have the same length'
k = len(x_values)
return sum(_basis(j)*y_values[j] for j in xrange(k))
您可以通过以下方式确认:
>>> interpolate(1,[1,2,4],[1,0,2])
1.0
>>> interpolate(2,[1,2,4],[1,0,2])
0.0
>>> interpolate(4,[1,2,4],[1,0,2])
2.0
>>> interpolate(3,[1,2,4],[1,0,2])
0.33333333333333331
所以结果是基于通过给定点的多项式的插值。在这种情况下,这 3 个点定义了一条抛物线,前 3 个测试表明对于给定的 x_value 返回了规定的 y_value。
关于python - Python 中的拉格朗日插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4003794/