“lagrange”返回的多项式不计算插值点

2024-10-06 15:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在以下代码上:

import numpy as np
from scipy.interpolate import lagrange
def fib(n):
     a, b = 0, 1
     for _ in range(n):
         a, b = b, a+b
     return a
x = np.array(range(64))
y = np.array([fib(n) for n in xrange(64)])
P = lagrange(x, y)
print P(10)

我使用scipy在64个点上插值函数(fib),从而创建一个多项式P。因此,我期望,P(n) == fib(n)对于任何0 <= n < 64。相反,例如,对于P(10),我得到的是-248014823183360.0,而不是55fib(10))。我想这是某个地方的精度错误,但我不确定在哪里。如何构造满足此期望的多项式函数P?你知道吗


Tags: 函数代码infromimportnumpyforas
1条回答
网友
1楼 · 发布于 2024-10-06 15:26:56

你可以试试这个numpy.polyfit公司在多项式秩较高时哪个更稳定

import numpy as np
from scipy.interpolate import lagrange

N = 30

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a+b
    return a


x = np.arange(N)
y = np.array([fib(i) for i in x])


P = np.polyfit(x, y, N)

n = int(N/2)
print ((y[n], np.polyval(P, n))) 

L = lagrange(x, y)
print ((y[n], L(n)))

610609.9896美元

610,-645662.4698毫米

除此之外,我要说的是,多项式拟合在大量的点上很少是一个好的解决方案。如果你对斐波那契级数感兴趣(或者只是一个例子?),您可以使用基于黄金数幂的分析公式,您可以导出浮动索引(请查看Fibonacci Wikipedia页面)。你知道吗

相关问题 更多 >