一、拉格朗日的基本思想:
二、线性插值
三、多个点
四、代码实现
def lagrange(xx,y):
l=len(y)
l_n = 0
for k in range(l):
xxx=xx.copy()
x_k = xxx[k]
xxx.pop(k)
l_k = 1
for i in range(len(xxx)):
l_k *= (x - xxx[i]) / (x_k -xxx[i])
l_n += y[k] * l_k
return expand(l_n)
五、完整代码
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sympy import expand
from sympy.abc import x
xx=[]
for i in range(7):
xx.append(data['x'][i])
y=[]
for j in range(7):
y.append(data['y'][j])
def lagrange(xx,y):
l=len(y)
l_n = 0
for k in range(l):
xxx=xx.copy()
x_k = xxx[k]
xxx.pop(k)
l_k = 1
for i in range(len(xxx)):
l_k *= (x - xxx[i]) / (x_k -xxx[i])
l_n += y[k] * l_k
return expand(l_n)
lagrange_interpolation_polynomial = lagrange(xx, y)
print("拉格朗日插值多项式为:",lagrange_interpolation_polynomial)
x2=np.linspace(-1,4,100)
y1=[]
for i in range(len(x2)):
y1.append(lagrange_interpolation_polynomial.subs(x,x2[i]))
print(y1)
#绘制散点图,逼近函数
plt.figure(figsize=(8,4))
plt.scatter(xx,y,c='red')
plt.plot(x2,y1,'-')
plt.show()
六、pop()函数
七、结果展示