资源描述:
《数值计算上机题_参考解答》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、实验一拉格朗日插值、分段线性插值、三次样条插值的比较一、问题提出选择函数y=exp(-x2)(-2≤x≤2),在n个节点上(n不要太大,如5~11)用拉格朗日、分段线性、三次样条三种插值方法,计算m个插值点的函数值(m要适中,如50~100)。二、要求通过数值和图形输出,将三种插值结果与精确值进行比较。适当增加n,在作比较,由此作初步分析。三、问题的解答为统一起见,认为题目中的节点指的是中间节点,插值时还要考虑两端点的函数值,故原题目中有n+2个插值节点。以下给出题目所需的MATLAB函数,其中参数count_knot表示题目中的n,count_d
2、ot表示题目中的m。functionresult=campare3inter(count_knot,count_dot)%count_knot中间节点的个数%count_dot拟合的函数值的个数clfknot=linspace(-2,2,count_knot+2);x=-2:0.01:2;y=exp(-x.^2);y0=exp(-knot.^2);plot(x,y,knot,y0,'ro');%,holdon;x_new=linspace(-2,2,count_dot);y_real=exp(-x_new.^2);%Lagrange插值y_lagr
3、ange=lagrange(knot,y0,x_new);plot(x_new,y_lagrange,'k');holdon;%分段线性插值y_line=zeros(1,length(x_new))count_1=1;forj=1:count_dotfori=1:count_knot+1if((x_new(j)>=knot(i))&((x_new(j)<=knot(i+1))))%直线的点斜式方程y_line(count_1)=((y0(i)-y0(i+1))/(knot(i)-knot(i+1)))*(x_new(j)-knot(i))+y0(i
4、);count_1=count_1+1;break;endendendplot(x_new,y_line,'b');holdon;%三次样条插值y_temp=[0y00];pp=csape(knot,y_temp,'second');[breaks,coefs,npolys,ncoefs,dim]=unmkpp(pp);count=1;forj=1:count_dotfori=1:count_knot+1if((x_new(j)>=knot(i))&((x_new(j)<=knot(i+1))))y_spline(count)=polyval(
5、coefs(i,:),x_new(j)-knot(i));count=count+1;break;endendendplot(x_new,y_spline,'g');%输出原函数值和三种插值函数值的比较结果result=[y_real'y_lagrange'y_line'y_spline']图形输出(n=5,m=50)10.90.80.70.60.50.40.30.20.10-2-1.5-1-0.500.511.52绿色:节点和exp(-x2)。黑色:Lagrange插值。蓝色:分段线性插值。红色:三次样条exp(-x2)拉格朗日插值分段线性插
6、值三次样条插值0.0183160.0183160.0183160.0183160.025220.0768580.0367680.0269420.0342660.107970.0552210.0364660.0459420.12190.0736740.0477850.060780.12690.0921270.0617970.0793450.129470.110580.0793980.102210.134510.129030.101490.129920.145550.147490.128960.162960.164880.165940.162710.2
7、01690.193760.217190.203470.246330.232560.275010.250770.296860.280880.332830.303660.353020.337740.390640.36120.414240.401690.448460.422440.479650.470910.506280.486440.548040.543360.564090.552250.617880.616840.621910.618930.68740.689130.670470.685470.754610.758010.714410.750350.
8、817440.821410.758350.81166exp(-x2)拉格朗日插值分段线性插值三次样条插值0.873770.