python 实现
方法一:
#bao
from scipy.interpolate import lagrange
x=[1,3,5]
y=[2,10,1]
print(lagrange(x,y))#拟合曲线
print(lagrange(x,y)(10))#估值`
结果:
2
-2.125 x + 12.5 x - 8.375
-95.875
方法二:
#python
import numpy
import matplotlib
from matplotlib import pyplot
x=[1,3,5]
y=[2,10,1]
def lagrange_interploate(x1):
P=[]
L_n=0
for i in range(len(x)):
numerator=1
denominator=1
for j in range(len(x)):
if j!=i:
numerator*=(x1-x[j])
denominator*=(x[i]-x[j])
P.append(numerator/denominator)
for i in range(len(x)):
L_n+=y[i]*P[i]
return round(L_n,3)
print(lagrange_interploate(10))
结果:
-95.875
拟合曲线图像:
x2=numpy.linspace(-10,10,20,endpoint=False)
print(x2)
y2=[]
for i in range(len(x2)):
y2.append(lagrange_interploate(x2[i]))
print(y2)
pyplot.plot(x2,y2)
pyplot.scatter(x,y,marker='.')
pyplot.show()