【MATLAB 】逐步搜索法、⼆分法、⽐例求根法、⽜顿法、弦截法求⽅程的根本⽂为《数值计算⽅法》的作业之⼀
之⼆:
之三:
收敛性⽐较
分别⽤逐步搜索法、⼆分法、⽐例求根法、⽜顿法、弦截法求下列⽅程的根,并分别画出⼏种⽅法所求根的收敛速度对⽐图(即画出相对误
差随迭代步数的变化趋势图)
代码
f (x )=cos (x )−x
f (x )=x −121
clear
% f(x)=0
f = @(x)cos(x)- x
x_left =-1;
x_right =2;
stepsMax=15;
% 逐步搜索法、⼆分法、⽐例求根法、⽜顿法、弦截法error errors = zeros(stepsMax,5);
syms x
df = matlabFunction(diff(f(x)))% 求导
if(f(x_left)* f(x_right)>=0)
disp("f(x_left) * f(x_right) >= 0")
end
% 逐步搜索法
a = x_left;
b = x_right;
h =(x_right - x_left)/stepsMax;
for i =1:stepsMax
c = a + h;
errors(i,1)= f(c);
if f(c)==0
break;
elseif f(c)*f(b)<0
a = c;
else
b = c;
end
end
% ⼆分法
a = x_left;
b = x_right;
for i =1:stepsMax
c =(a+b)/2;
errors(i,2)= f(c);
if f(c)==0
break;
elseif f(c)*f(b)<0
a = c;
else
b = c;
end
end
% ⽐例求根法
a = x_left;
b = x_right;
for i =1:stepsMax
c = a - f(a)/(f(a)-f(b))*(a-b);
errors(i,3)= f(c);
if f(c)==0
break;
elseif f(c)*f(b)<0
a = c;
else
b = c;
end
end
% ⽜顿法
c = x_right;
for i =1:stepsMax
c = c - f(c)./df(c);
errors(i,4)= f(c);
if f(c)==0
break;
end
matlab求导end
% 弦截法
c = x_right;
d = x_left;
for i =1:stepsMax
temp = d;
d = d - f(d)*(c-d)/(f(c)-f(d));
c = temp;
errors(i,5)= f(d);
if f(c)==0
break;
end
end
figure
hold on
errors =abs(errors);
for i =1:5
semilogy(errors(:,i),".-"); end