本实验为2022级电子科大软件工程(工业软件)的数值计算课程实验,代码仅供参考。
实验一:编程实践二分法、不动点迭代、牛顿法及弦截法
实验目的:
1.能程序实现非线性方程各种求根方法
2.理解迭代法的收敛、局部收敛及收敛阶
实验环境:matlab
实验要求:求方程x3-x-1=0在x=1.5附近的一个根。构造三种迭代格式,判断他们的收敛性,并选取一种有效的迭代格式编程实践。
一、二分法
实验步骤:
实验代码:
function result=bisection(a,b,p,count)
%p精度 count最多迭代次数
for i=1:count
c=(b+a)/2;
f1=a^3-a-1;
f2=b^3-b-1;
f3=c^3-c-1;
if f1*f3<0
b=c;
elseif f2*f3<0
a=c;
end
d=(a+b)/2;
fprintf('迭代次数为%d\t',i);
fprintf('迭代得到的数值为%d\n',d);
if abs(a-b)<p
d=(x+y)/2;
fprintf('迭代次数为%d\t',i);
fprintf('迭代最终得到的数值为%d\n',d);
break;
end
end
二、不动点迭代法
实验步骤:
实验代码:
function result=fixed_point(x0,p,count)
%p精度 count最多迭代次数
for i=1:count %迭代次数
x1=1+1/x0^3; %有效迭代方法
if abs(x1-x0)<p %判断精度
break;
end
x0=x1;
fprintf('迭代次数为%d\t',i);
fprintf('迭代得到的数值为%d\n',x0);
end
result=x1;
fprintf('迭代次数为%d\t',i);
fprintf('迭代最终得到的数值为%d\n',result);
end
三、牛顿法
实验步骤:
实验代码:
function result=newton(x0,p,count)
%牛顿法
for i=1:count
f=x0^3-x0-1;
f1=3*x0^2-1;
x1=x0-f/f1;
if abs(x1-x0)<p
break;
end
x0=x1;
fprintf('迭代次数为%d\t',i);
fprintf('迭代得到的数值为%d\n',x0);
end
result=x0;
fprintf('迭代次数为%d\t',i);
fprintf('迭代最终得到的数值为%d\n',result);
end
四、弦截法
实验步骤:
实验代码:
function result=secant(x0,x1,p,count)
%弦截法
for i=1:count
f0=x0^3-x0-1;
f1=x1^3-x1-1;
x2=x1-f1*(x1-x0)/(f1-f0);
if abs(x2-x1)<p
break;
end
x0=x1;
x1=x2;
fprintf('迭代次数为%d\t',i);
fprintf('迭代得到的数值为%d\n',x2);
end
result=x2;
fprintf('迭代次数为%d\t',i);
fprintf('迭代最终得到的数值为%d\n',result);
end
写在最后:代码仅供参考,请根据实际需要进行修改,请认真完成实验报告(打分主要看实验报告)。