Matlab-2:二分法工具箱

 1 function g=dichotomy(f,tol)
 2 %this routine uses bisection to find a zero of user-supplied
 3 %continuous function f.the user must supply two points an and bn
 4 %such that f(an) and f(bn) have different signs .the user also
 5 %supplies a convergence tolerance delta .
 6 %this progress is writen by H.D.dong
 7 % tic;
 8 % clear
 9 % clc
10 % f=inline('x^3-x^2-1');
11 % f=inline('x^6-x-1');
12 % f=inline('x^2+1');
13 % % h=inline('x^3-x^2-1');
14 % % tol=1e-14;
15 % % Provides a zero-point presence interval
16 % % %
17 % % an=1;
18 % % bn=2;
19 % % %
20 % % root=dichotomy(h,tol)
21 an=1;
22 bn=2;
23 root=0;
24 if f(an)==0,root=an;bn=root;return;
25 elseif f(bn)==0,root=bn;an=root;return;
26 elseif sign(f(an))==sign(f(bn)),fprintf('There is no solution in this equation!');
27     %%
28 %Above showed:there have considered that we have found the root in the first step.
29 else
30     k=0;
31 while (bn-an)>=tol
32 midpoint=(bn+an)/2;k=k+1;F(k)=f(midpoint);
33     if f(midpoint)==0,root=midpoint;an=root;bn=root;break;
34     elseif sign(f(midpoint))~=sign(f(an)),bn=midpoint;
35     else
36         an=midpoint;
37     end
38 end
39 root=(bn+an)/2;
40 end
41 g=root;
42 % toc;

 

posted @ 2017-03-05 17:09  胡冬冬  阅读(544)  评论(0编辑  收藏  举报