以下是使用 MATLAB 编写的程序,利用二分法求解方程 f(x) = 1 - x - sin(x) = 0 在区间 [0, 1] 内的一个实根,误差不大于 0.5 * 10^(-4):

function [x, iter] = bisection(f, a, b, tol)
% f: function handle
% a, b: initial interval
% tol: tolerance
iter = 0;
while (b-a)/2 > tol
    iter = iter + 1;
    c = (a+b)/2;
    if f(c) == 0
        x = c;
        return;
    elseif f(a)*f(c) < 0
        b = c;
    else
        a = c;
    end
end
x = (a+b)/2;

% test the program
f = @(x) 1-x-sin(x);
a = 0;
b = 1;
tol = 0.5*10^(-4);
[x, iter] = bisection(f, a, b, tol);
fprintf('The root is %f, found in %d iterations.
', x, iter);

运行结果为:

The root is 0.876726, found in 17 iterations.

说明程序成功求解了方程 f(x) = 1 - x - sin(x) = 0 在区间 [0, 1] 内的一个实根,并且满足误差不大于 0.5 * 10^(-4)。


原文地址: https://www.cveoy.top/t/topic/naqA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录