Python中的Lagrange插值 [英] Lagrange interpolation in Python

查看:188
本文介绍了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.

这篇关于Python中的Lagrange插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆