1/5数值分析实验报告姓名忘川学号1205025106系别数学系班级12级主讲教师指导教师实验日期2014/6/25专业信息与计算科学专业课程名称数值分析同组实验者无一、实验名称:实验四、三次样条插值实验二、实验目的:1.掌握三次样条插值的运用;2.了解拉格朗日插值在高次上的误差。三、实验内容及要求:给定函数21(),[5,5],1fxxx=?+节点5(0,1,,10),kxkk=-+=L(1)编写三次样条程序求10()Sx,取101010()()(0,1,,10),(5)(5),(5)(5).kkSxfxkSfSfⅱⅱ==-=-=L(2)作原函数()fx、Langrage插值函数10()Lx和三次样条插值函数10()Sx的图像,并比较它们的区别。附:算法描述:三次样条插值(CubicSplineInterpolation)PURPOSE:Tofindapiecewisecubicsplinefunction331111()(-)(-)()()()()6666iiiiiiiiiiiiiiiiMMyMyMSxxxxxhxxhxxhhhh.(1iixxx,0,1i,…1,n).whereniMxSii,,1,0,and''11()iiiiiixxxxSxMMhh1[,],iixxx0,1i,…1,n.INPUT:interpolatedpointsiiyx,;clampedboundarycondition00(),()innSxySxy.OUTPUT:niMi,,1,0Step1For1,,2,1ni1111111(1)6()iiiiiiiiiiiiiiiiiiihhhhhhyyyyhhhh2/5Step2Byclampedboundarycondition,Set01n,1000116()yyyhh,16()nnnnnnyyyhhStep3Solvetri-diagonalsystem00011112222111122222nnnnnnnMMMMMStep4OutputniMi,,1,0.Stop四、实验步骤(或记录)(1)编写三次样条程序求10()Sx,取101010()()(0,1,,10),(5)(5),(5)(5).kkSxfxkSfSfⅱⅱ==-=-=L程序如下:function[s,m]=selfspline(x0,y0,df,x,conds)n=length(x0);h=diff(x0);b=ones(1,n)*2;forj=2:n-1a(j)=h(j-1)/(h(j-1)+h(j));c(j)=h(j)/(h(j-1)+h(j));d(j)=6*(h(j-1)*(y0(j+1)-y0(j))-h(j)*(y0(j)-y0(j-1)))/(h(j)*h(j-1)*(h(j)+h(j-1)));enda(1:n-2)=a(2:n-1);switchcondscase1a(n-1)=1;c(1)=1;d(1)=6*((y0(2)-y0(1))/(x0(2)-x0(1))-df(1))/(x0(2)-x0(1));d(n)=6*(df(2)-(y0(n)-y0(n-1))/(x0(n)-x0(n-1)))/(x0(n)-x0(n-1));case2a(n-1)=0;c(1)=0;d(1)=2*df(1);d(n)=2*df(2);otherwiseerror('conds值错误,conds只能为1或2')endfori=2:nr=a(i-1)/b(i-1);b(i)=b(i)-r*c(i-1);3/5d(i)=d(i)-r*d(i-1);endm(n)=d(n)/b(n);fori=n-1:-1:1m(i)=(d(i)-c(i)*m(i+1))/b(i);endforj=1:length(x)fori=1:n-1ifx(j)=x0(i)&x(j)=x0(i+1)s(j)=m(i)*(x0(i+1)-x(j))^3/(6*h(i))+m(i+1)*(x(j)-x0(i))^3/(6*h(i))+(y0(i)-m(i)*h(i)^2/6)*(x0(i+1)-x(j))/h(i)+(y0(i+1)-m(i+1)*h(i)^2/6)*(x(j)-x0(i))/h(i);endendend在matlab的命令窗口输入:k=0:10;x0=-5+k;y0=1./(x.^2+1);x=-5:0.5:5;y=1./(x.^2+1);df=diff(y)得到如下数据:df=0.00860.01180.01660.02450.03790.06210.10770.19230.30000.2000-0.2000-0.3000-0.1923-0.1077-0.0621-0.0379-0.0245-0.0166-0.0118-0.0086(2)作原函数()fx、Langrage插值函数10()Lx和三次样条插值函数10()Sx的图像,并比较它们的区别。先写拉格朗日插值的程序,如下:4/5functiony=lagr1(x0,y0,x)n=length(x0);m=length(x);fori=1:mz=x(i);s=0.0;fork=1:np=1.0;forj=1:nifj~=kp=p*(z-x0(j))/(x0(k)-x0(j));endends=p*y0(k)+s;endy(i)=s;endend然后直接在matlab的命令窗口输入:x0=[-5-4-3-2-1012345];y0=1./(x0.^2+1);x=-5:0.01:5;df=diff(y0);conds=1;y=selfspline(x0,y0,df,x,conds);y1=1./(x.^2+1);y2=lagr1(x0,y0,x);plot(x,y1,'b',x,y,'y-',x,y2,'r:')legend('原函数','三次样条插值','Lagrange插值')即可得到以下图形:5/5-5-4-3-2-1012345-0.500.511.52原函数三次样条插值Lagrange插值(3)分析结果:根据图像可知,用拉格朗日插值函数进行插值时,在次数较高时会出现龙格现象,导致其值与原函数相差甚大,在一定范围内插值拟合效果不好,而三次样条插值函数可以很好地接近原函数且光滑性较好,是比较理想的插值函数。五、教师评语(或成绩)教师签字:年月日