我尝试在 python 中编码拉格朗日插值,以便它返回多项式系数列表,但是当我显示曲线时,它根本不是我所期望的。大多数编码此插值的人仅在一个点上对其进行评估,但我想获得系数列表。
from math import *
import numpy as np
import matplotlib.pyplot as plt
def P(l,x:float): # l is the list of coeffcients from lowest to highest degree
res=0
for n,i in enumerate(l):
res+=i*x**n # evaluate the equation in x
return res
def Lagrange(xtab,ytab): # return the Lagrange interpolation
X=np.poly1d([1,0])
P=0
for i in range(len(ytab)):
Li=1
for j in range(len(ytab)):
if i==j:
continue
else :
Li=Li*((X-xtab[j])/(xtab[i]-xtab[j]))
P+=Li*ytab[i]
return Li
def points(l,N,h): # return a list of points of a known polynomial randomized a little by h
xtab=np.linspace(-10,10,N)
ytab=np.zeros(N)
for k,x in enumerate(xtab):
ytab[k]=P(l,x)
for i,y in enumerate(ytab):
ytab[i]= y + np.random.uniform(-h,h)
return xtab,ytab
N=20
xtab,ytab=points([3,0,-2],N,0.2)
L=Lagrange(xtab,ytab)
ylagrange=np.polyval(L,xtab2)
plt.figure()
plt.plot(xtab1,ytab1)
plt.plot(xtab2,ylagrange)
plt.show()
当我显示曲线时,它没有按照应有的方式遵循给定的点。代码确实给出了一个方程,所以我真的不知道出了什么问题。