Python 中的拉格朗日插值
我想用拉格朗日方法插值多项式,但此代码不起作用:
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< /a>,但是当我运行它时,我在第 3 行收到一个 IndexError!
谢谢
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))
I followed Wikipedia, but when I run it I receive an IndexError at line 3!
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
您可以按如下方式确认:
因此结果是基于经过给定点的多项式的插值。在本例中,这 3 个点定义了一条抛物线,前 3 个测试显示针对给定的 x_值返回了指定的 y_值。
Try
You can confirm it as follows:
So the result is the interpolated value based on the polynomial that goes through the points given. In this case, the 3 points define a parabola and the first 3 tests show that the stated y_value is returned for the given x_value.
我迟到了近十年,但我发现这是在寻找拉格朗日插值的简单实现。 @smichr 的答案很好,但是 Python 有点过时了,我还想要一些可以与 np.ndarrays 很好地配合的东西,这样我就可以轻松地进行绘图。也许其他人会发现这很有用:
I'm almost a decade late to the party, but I found this searching for a simple implementation of Lagrange interpolation. @smichr's answer is great, but the Python is a little outdated, and I also wanted something that would work nicely with
np.ndarrays
so I could do easy plotting. Maybe others will find this useful:检查索引,维基百科说“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 bek = len(x_values) - 1
if you followed the formula exactly.此代码与
Python 3
兼容:This code is compatible with
Python 3
: