使用matlab程式利用二分法來解題

請問大家在matlab中如何使用二分法

解決此題

f(x)=x^8+5x^7+2x^5-x^4+4x^3-2x^2+6

謝謝大家!!

1 個解答

評分
  • 老師
    Lv 7
    1 0 年前
    最佳解答

    二分法程式function r = bisect(fun,xb,xtol,ftol,verbose)% bisect  Use bisection to find a root of the scalar equation f(x) = 0%% Synopsis:  r = bisect(fun,xb)%            r = bisect(fun,xb,xtol)%            r = bisect(fun,xb,xtol,ftol)%            r = bisect(fun,xb,xtol,ftol,verbose)%% Input: fun     = (string) name of function for which roots are sought%        xb      = vector of bracket endpoints. xleft = xb(1), xright = xb(2)%        xtol    = (optional) relative x tolerance.    Default:  xtol=5*eps%        ftol    = (optional) relative f(x) tolerance. Default:  ftol=5*eps%        verbose = (optional) print switch. Default: verbose=0, no printing%% Output:  r = root (or singularity) of the function in xb(1) <= x <= xb(2)if size(xb,1)>1, warning('Only first row of xb is used as bracket');  endif nargin < 3,  xtol = 5*eps;  endif nargin < 4,  ftol = 5*eps;  endif nargin < 5,  verbose = 0;   endxeps = max(xtol,5*eps);         %  Smallest tolerances are 5*epsfeps = max(ftol,5*eps);a = xb(1,1); b = xb(1,2);       %  Use first row if xb is a matrixxref = abs(b - a);              %  Use initial bracket in convergence testfa = feval(fun,a);   fb = feval(fun,b);fref = max([abs(fa) abs(fb)]);  %  Use max f in convergence testif sign(fa)==sign(fb)           %  Verify sign change in the interval  error(sprintf('Root not bracketed by [%f, %f]',a,b));endif verbose  fprintf('\nBisection iterations for %s.m\n',fun);  fprintf('   k       xm            fm\n');endk = 0;  maxit = 50;      %  Current and max number of iterationswhile k < maxit  k = k + 1;  dx = b - a;  xm = a + 0.5*dx;       %  Minimize roundoff in computing the midpoint  fm = feval(fun,xm);  if verbose, fprintf('%4d  %12.4e  %12.4e\n',k,xm,fm); end  if (abs(fm)/fref < feps) | (abs(dx)/xref < xeps) % True when root is found    r = xm;  return;  end  if sign(fm)==sign(fa)    a = xm;  fa = fm;    %  Root lies in interval [xm,b], replace a and fa  else    b = xm;  fb = fm;    %  Root lies in interval [a,xm], replace b and fb  endendwarning(sprintf('root not within tolerance after %d iterations\n',k));---------------------------------------------

    2006-10-19 21:18:56 補充:

    執行二分法必須先找到一個區域[a,b] 此區域使得f(a)*f(b)<0 所以我們往往先畫圖 觀察一下

    >> clear

    >> f=inline('x.^8+5*x.^7+2*x.^5-x.^4+4*x.^3-2*x.^2+6');

    >> x=linspace(-6,-3);

    >> fx=feval(f,x);

    >> plot(x,fx), grid on

    2006-10-19 21:19:07 補充:

    由所畫出的圖可以觀察到 a=-5.5, b=-4.5 滿足 f(a)*f(b)<0 所以可以利用二分法求出一根

    >> x=bisect(f,[-5.5,-4.5])

    x =

    -5.0912

    2006-10-19 21:19:33 補充:

    如果你找的點不滿足f(a)*f(b)<0 程式會給出錯誤訊息

    >> x=bisect(f,[-6.5,-5.5])

    ??? Error using ==> bisect

    Root not bracketed by [-6.500000, -5.500000]

    觀察圖形後 可以找到另一個根

    >> x=bisect(f,[-3,0])

    x =

    -0.8279

    2006-10-19 21:20:28 補充:

    回答限制2000字

    實在放不下了

    只能放在意見中

還有問題?馬上發問,尋求解答。