matlab 二分法程序
时间: 2023-12-07 15:39:44 浏览: 92
以下是一个简单的Matlab二分法程序的示例:
```matlab
function [root, fx, ea, iter] = bisect(func, xl, xu, es, maxit)
% bisect: root location zeroes
% [root, fx, ea, iter] = bisect(func, xl, xu, es, maxit): uses bisection
% method to find the root of func
% input:
% func = name of function
% xl, xu = lower and upper guesses
% es = desired relative error (default = 0.0001%)
% maxit = maximum allowable iterations (default = 50)
% output:
% root = real root
% fx = function value at root
% ea = approximate relative error (%)
% iter = number of iterations
% check for proper sign change
test = func(xl) * func(xu);
if test > 0
error('no sign change')
end
% set defaults
if nargin < 4 || isempty(es)
es = 0.0001;
end
if nargin < 5 || isempty(maxit)
maxit = 50;
end
% initialization
iter = 0;
xr = xl;
ea = 100;
% loop
while (1)
xrold = xr;
xr = (xl + xu) / 2;
iter = iter + 1;
if xr ~= 0
ea = abs((xr - xrold) / xr) * 100;
end
test = func(xl) * func(xr);
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
if ea <= es || iter >= maxit
break
end
end
% output
root = xr;
fx = func(xr);
end
```
这个程序使用了bisection方法来寻找函数的根。它需要输入函数名,下限和上限猜测值,所需的相对误差和最大迭代次数。输出是根,函数值,近似相对误差和迭代次数。
阅读全文