给出matlab的二分法求根的代码
时间: 2023-12-05 10:03:39 浏览: 99
以下是一个简单的 Matlab 代码示例,使用二分法求解函数 $f(x)$ 的根:
```matlab
function [root, fx, ea, iter] = bisection(f, xl, xu, es, maxit)
% Bisection method for root finding
% Input:
% - f: the function handle to the function to be solved
% - xl, xu: the lower and upper bounds of the interval containing the root
% - es: the desired relative error (default: 0.0001%)
% - maxit: the maximum number of iterations (default: 50)
% Output:
% - root: the estimated root of f(x)
% - fx: the function value at the root
% - ea: the approximate relative error (%)
% - iter: the number of iterations performed
if nargin < 4 || isempty(es), es = 0.0001; end
if nargin < 5 || isempty(maxit), maxit = 50; end
% check if the root is bracketed
if f(xl) * f(xu) > 0
error('The root is not bracketed!');
end
% initialize variables
iter = 0;
xr = xl;
ea = 100;
% main loop
while ea > es && iter < maxit
xrold = xr;
xr = (xl + xu) / 2;
iter = iter + 1;
if xr ~= 0
ea = abs((xr - xrold) / xr) * 100;
end
test = f(xl) * f(xr);
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
end
% output results
root = xr;
fx = f(xr);
end
```
使用示例:
```matlab
% define the function to be solved
f = @(x) x^2 - 2;
% call the bisection function
[root, fx, ea, iter] = bisection(f, 0, 2, 0.0001, 50);
% display results
fprintf('Root: %f\n', root);
fprintf('Function value: %f\n', fx);
fprintf('Approximate relative error: %f%%\n', ea);
fprintf('Number of iterations: %d\n', iter);
```
其中,`f` 是要求解根的函数句柄,`xl` 和 `xu` 是根所在的区间的下限和上限,`es` 是期望的相对误差,`maxit` 是最大迭代次数。函数返回根 `root`、函数值 `fx`、近似相对误差 `ea` 和迭代次数 `iter`。