【问题标题】:Bisection method in matlabmatlab中的二分法
【发布时间】:2020-10-18 05:23:31
【问题描述】:
function r=bisection(f,a,b,tol,nmax)
% function r=bisection(f,a,b,tol,nmax)
% inputs: f: function handle or string
% a,b: the interval where there is a root
% tol: error tolerance
% nmax: max number of iterations
% output: r: a root
c=(a+b)/2;
nit=1;
if f(a)*f(b)>0
    r=NaN;
    fprintf("The bisection method failed \n")
else
    while(abs(f(c))>=tol && nit<nmax)
        if (f(c)*f(a))<0
            c=(a+c)/2;
        elseif (f(c)*f(b))<0
            c=(a+b)/2;
        elseif f(c)==0
            break;
        end
        nit=nit+1;
    end
    r=c;
end

以上是我的二分法代码。我对为什么该代码不能正常工作感到困惑。 f(c) 的结果在运行时每 3 次重复一次。谁能告诉我为什么这段代码不起作用?

【问题讨论】:

    标签: matlab bisection


    【解决方案1】:

    在您的解决方案中,您忘记考虑需要在每次迭代时将区间的两个极值 ab 之一重置为 c

    function r=bisection(f,a,b,tol,nmax)
    % function r=bisection(f,a,b,tol,nmax)
    % inputs: f: function handle or string
    % a,b: the interval where there is a root
    % tol: error tolerance
    % nmax: max number of iterations
    % output: r: a root
    c=(a+b)/2;
    nit=1;
    if f(a)*f(b)>0
        r=NaN;
        fprintf("The bisection method failed \n")
    else
        while(abs(f(c))>=tol && nit<nmax)
            if (f(c)*f(a))<0
                b=c;                % new line
                c=(a+c)/2;            
            elseif (f(c)*f(b))<0
                a=c;                % new line
                c=(c+b)/2;
            elseif f(c)==0
                break;
            end
            nit=nit+1;
        end
        r=c;
    end
    
    

    【讨论】:

      【解决方案2】:

      我认为您需要更新下一轮二等分的边界(在您的 while 循环内),如下所示

      function r = bisection(f,a,b,tol,nmax)
      c=mean([a,b]);
      nit=1;
      if f(a)*f(b)>0
          r=NaN;
          fprintf("The bisection method failed \n")
      else
          while(abs(f(c))>=tol && nit<nmax)
              if (f(c)*f(a))<0
                  b=c;                      
              elseif (f(c)*f(b))<0
                  a=c;
              elseif f(c)==0
                  break;
              end
              c=mean([a,b]);
              nit=nit+1;
          end
          r=c;
      end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-07
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        • 2012-01-25
        • 2013-07-04
        • 2014-01-03
        • 2020-08-27
        相关资源
        最近更新 更多