matlab中的二分法

Bisection method in matlab

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)的结果每三次重复运行这个。谁能告诉我为什么这段代码不起作用?

在您的解决方案中,您忘记考虑需要在每次迭代时将间隔的两个极端 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

我认为您需要更新下一轮二等分的边界(在您的 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