实验题目:
实验代码:
首先先写出4个迭代函数
function [result] = func_1 (x,flag) %第一种迭代函数 result=(x^2+2)/3; endfunction function [result] = func_2 (x) %第二种迭代函数 result=sqrt(3*x-2); endfunction function [result] = func_3 (x) %第三种迭代函数 result=3-(2/x); endfunction function [result] = func_4 (x) %第四种迭代函数 result=(x^2-2)/(2*x-3); endfunction然后写出不动点迭代函数 function [k,result] = fixed_point_iter (my_func,x0,precision) %%my_func是迭代函数,x0是初始迭代值,precision是精度要求 flag=0; %迭代失败标志,0表示迭代成功,1表示迭代失败 x1=k=0; %k用于记录迭代次数 now_pre=abs(2-x0); %当前的x1-x0的差 fro_pre=now_pre; %前一次误差 while now_pre >= precision k++; %迭代次数加一 x1=my_func(x0); now_pre=abs(2-x1); %计算当前误差 if(now_pre > fro_pre || (x1==x0 && x1!=2)) %如果误差反而增大,说明在发散 flag=1; break; endif x0=x1; endwhile if flag==0 result=x1; else result=k=-1; endif endfunction写出测试 %%第三次实验课(实验2.1) clc clear %在此设置参数 precision=(1/10^5); %精度 x0=[0.5:0.05:2.5]; f_1=@func_1; %四种迭代函数句柄 f_2=@func_2; f_3=@func_3; f_4=@func_4; k1=k2=k3=k4=zeros(1,length(x0)); for i=1:1:length(x0) [k1(1,i),x1]=fixed_point_iter(f_1,x0(1,i),precision); [k2(1,i),x2]=fixed_point_iter(f_2,x0(1,i),precision); [k3(1,i),x3]=fixed_point_iter(f_3,x0(1,i),precision); [k4(1,i),x4]=fixed_point_iter(f_4,x0(1,i),precision); endfor %绘图 hold on plot(x0,k1,'-co') plot(x0,k2,'-r^') plot(x0,k3,'-b^') plot(x0,k4,'-k+') title("The convergence rate of four functions") xlabel('X0') ylabel('Number of iterations') legend('func_1','func_2','func_3','func_4')实验结果: