python - Python 中的拉格朗日插值

标签 python interpolation polynomial-math

我想用拉格朗日方法对多项式进行插值,但这段代码不起作用:

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/

相关文章:

python (1040, 'Too many connections')

python - 在哪里可以找到 python 中的自然邻域插值

c - 用 c 中的两个数组对 n 的所有值进行插值的最佳方法是什么?

java - 用 Java 求解多项式方程

matlab - 需要使用切比雪夫多项式基础来拟合多项式

python - python pandas groupby 中的 'AAPL' 和 ['AAPL' ] 有什么区别

python - 如何从另一个目录将图像导入到 pygame 中?

python - 向网站输入数据并提取结果

c++ - 反距离加权插值

python - 为什么在 python 中解决 Xc=y 的不同方法在不应该给出不同的解决方案时给出不同的解决方案?