改过来了
% BISECTION finds function zeros
% [ZERO,RES,NITER]=BISECTION(FUN,A,B,TOL,NITER_MAX)
% Tries to find a zero of the continuous fuction in the interval [A,B]
% using the bisection method.
function [zero,res,niter]=...
bisection(fun,a,b,tol,niter_max,varargin)
x=[a,(a+b)*0.5,b];
fx=feval(fun,x,varargin{:});
if fx(1)*fx(3)>0
error(['The sign of the function at the extrema of the interval',...
' must be different.'])
elseif fx(1)==0
zero=a;res=0;niter=0;
return
elseif fx(3)==0
zero=b;res=0;niter=0;
return
end
niter=0;
I=(b-a)*0.5;
while I>tol && niter
niter=niter+1;
if sign(fx(1))*sign(fx(2))<0
x(3)=x(2);
x(2)=x(1)+(x(3)-x(1))*0.5; %减少舍入误差
fx(3)=fx(2);
fx(2)=feval(fun,x(2),varargin{:});
I=(x(3)-x(1))*0.5;
elseif sign(fx(2))*sign(fx(3))<0
x(1)=x(2);
x(2)=x(1)+(x(3)-x(1))*0.5; %减少舍入误差
fx(1)=fx(2);
fx(2)=feval(fun,x(2),varargin{:});
I=(x(3)-x(1))*0.5;
else
I=0;
end
end
if I>tol
fprintf(['\n Bisection stopped without converqing desired '...
'tolerance because the max number of iterations was reached.\n'])
end
zero=x(2);x=x(2);res=feval(fun,x);
2009-4-2 09:19 上传
点击文件名下载附件
1.26 KB, 下载次数: 3783