MATLAB程序:逐步搜索法、二分法和迭代法求解方程根
使用MATLAB编写三个程序,分别实现以下三个功能,不要定义函数:
- 用逐步搜索法求方程f(x)=x^3-x-1=0的一个有根区间,要求有根区间的范围不得超过0.1
- 用二分法求解方程f(x)=1-x-sinx=0在区间[0,1]内的一个实根,使误差不大于0.5*10^-4
- 用迭代法求解方程f(x)=x^3-x-1=0在区间[1.4,1.6]上的根,要求保留至少5位有效数字
程序1:
x = -1:0.0001:2;
y = x.^3-x-1;
root1 = 0;
root2 = 0;
for i = 1:length(x)-1
if y(i)*y(i+1)<0
if root1 == 0
root1 = (x(i)+x(i+1))/2;
else
root2 = (x(i)+x(i+1))/2;
break
end
end
end
if abs(root2-root1)>0.1
disp('未找到有根区间')
else
fprintf('有根区间为[%f,%f]
',root1,root2)
end
程序2:
a = 0;
b = 1;
tol = 0.5*10^-4;
while b-a>tol
c = (a+b)/2;
if (1-c-sin(c))*(1-a-sin(a))<0
b = c;
else
a = c;
end
end
fprintf('方程的实根为%f
',c)
程序3:
x0 = 1.5;
tol = 0.5*10^-5;
f = @(x) x^3-x-1;
df = @(x) 3*x^2-1;
iter = 0;
while abs(f(x0))>tol
x1 = x0 - f(x0)/df(x0);
x0 = x1;
iter = iter+1;
end
fprintf('方程的根为%f,迭代次数为%d
',x0,iter)
原文地址: https://www.cveoy.top/t/topic/namg 著作权归作者所有。请勿转载和采集!