(一)Python
# lagrange插值画图版本
import matplotlib.pyplot as plt
import numpy as np
import math
from pylab import mpl
x=[0.32,0.34,0.36]
y=[0.314562,0.333487,0.352274]
x0 = np.arange(min(x), max(x)+0.01, 0.01)
def fun(x0,x,y):
sum=0
for i in range(len(x)):
m=1
n=1
for j in range(len(x)):
if j!=i:
m *= x0-x[j]
n *= x[i]-x[j]
l=y[i]*m/n
sum+=l
return sum
def function(date):
return fun(date,x,y)
plt.scatter(x,y,label="离散数据",color="red")
plt.plot(x0,fun(x0,x,y),label="langrage插值拟合曲线",color="black")
plt.scatter(0.3367,function(0.3367),label="预测函数点",color="blue")
plt.title("langrange插值法")
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.legend(loc="upper left")
plt.show()
运行结果为:
(二)MATLAB
function y=lagrange(x0,y0,x)
n = length(x);
y = zeros(n);
for i = 1:length(x0)
j_no_i=find((1:length(x0))~=i);
y1=1;
for j = 1:length(j_no_i)
y1 = y1.*(x-x0(j_no_i(j)));
end
y = y + y1*y0(i)/prod(x0(i)-x0(j_no_i));
end
end
在命令行窗口输入
x=[0.4 0.5 0.7 0.8]
y=[-0.916291 -0.693147 -0.356675 -0.223144]
lagrange(x,y,0.4)
可以得到
ans =
-0.9163