Python中的Lagrange插值

问题描述:

我想用Lagrange方法内插多项式,但是此代码不起作用:

I want to interpolate a polynomial with the Lagrange method, but this code doesn't work:

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

我关注了维基百科,但是当我运行它时,我在第3行收到了IndexError !

I followed Wikipedia, but when I run it I receive an IndexError at line 3!

谢谢

检查索引,维基百科说"k + 1个数据点",但如果您遵循k = len(x_values),则应将其设置为k = len(x_values) - 1.精确地计算公式.

Check the indices, Wikipedia says "k+1 data points", but you're setting k = len(x_values) where it should be k = len(x_values) - 1 if you followed the formula exactly.