matlab二分法tol,Matlab二分法

改过来了

%   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);

f5c3d56501a3d0261ce0cb81cbf824a7.gif

2009-4-2 09:19 上传

点击文件名下载附件

1.26 KB, 下载次数: 3783


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部