一、实验目的
在已知f(x),x∈[a,b]的表达式,但函数值不便计算,或不知f(x),x∈[a,b]而又需要给出其在[a,b]上的值时,按插值原则f(xi)= yi(i= 0,1…….,n)求出简单函数P(x)(常是多项式),使其在插值基点xi,处成立P(xi)= yi(i=0,1,……,n),而在[a,b]上的其它点处成立f(x)≈P(x).
二、实验原理
三、实验内容
求之f(x)=x4在[0,2]上按5个等距节点确定的Lagrange插值多项式.
四、实验程序
1 import matplotlib.pyplot as plt 2 from pylab import mpl 3 4 #计算插值多项式的系数。 5 x = [0, 0.5, 1, 1.5, 2] 6 y = [0, 0.0625, 1, 5.0625, 16] 7 8 def ParametersOfLagrangeInterpolation(data_x,data_y,size): 9 parameters=[] 10 11 i=0;#i用来控制参数的个数 12 while i < size: 13 j = 0;#j用来控制循环的变量做累乘 14 temp = 1; 15 while j < size: 16 if(i != j): 17 temp*=data_x[i]-data_x[j] 18 j+=1; 19 parameters.append(data_y[i]/temp) 20 i += 1; 21 return parameters 22 23 #计算拉格朗日插值公式的值。 24 25 def CalculateTheValueOfLarangeInterpolation(data_x,parameters,x): 26 returnValue=0 27 i = 0; 28 while i < len(parameters): 29 temp = 1 30 j = 0; 31 while j< len(parameters): 32 if(i!=j): 33 temp *=x-data_x[j] 34 j+=1 35 returnValue += temp * parameters[i] 36 i += 1 37 return returnValue 38 39 #将函数绘制成图像 40 def Draw(data_x,data_y,new_data_x,new_data_y): 41 plt.plot(new_data_x, new_data_y, label="拟合曲线", color="red") 42 plt.scatter(data_x,data_y, label="离散数据",color="yellow") 43 plt.scatter(1.75, 9.37890625, label="真实数据", color="orange") 44 plt.scatter(1.25, 2.44140625, color="green") 45 mpl.rcParams['font.sans-serif'] = ['SimHei'] 46 mpl.rcParams['axes.unicode_minus'] = False 47 plt.title("Lagrange插值拟合数据") 48 plt.legend(loc="upper left") 49 plt.show() 50 51 parameters=ParametersOfLagrangeInterpolation(x,y,5) 52 datax=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2] 53 datay=[] 54 for temp in datax: 55 datay.append(CalculateTheValueOfLarangeInterpolation(x,parameters,temp)) 56 x.append(1.75) 57 y.append(CalculateTheValueOfLarangeInterpolation(x,parameters,1.75)) 58 Draw(x,y,datax,datay) 59 print("得到的四次Lagrange插值多项式为:L(x) = %f(x-0)(x-1)(x-1.5)(x-2) + %f(x-0)(x-0.5)(x-1.5)(x-2) + %f(x-0)(x-0.5)(x-1)(x-2) + %f(x-0)(x-0.5)(x-1)(x-1.5)"%(parameters[1],parameters[2],parameters[3],parameters[4]))
五、运算结果
(1)图像
(2)运算结果
得到的四次Lagrange插值多项式为:L(x) = -0.166667(x-0)(x-1)(x-1.5)(x-2) + 4.000000(x-0)(x-0.5)(x-1.5)(x-2) + -13.500000(x-0)(x-0.5)(x-1)(x-2) + 10.666667(x-0)(x-0.5)(x-1)(x-1.5)