微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Matlab中的二分法

如何解决Matlab中的二分法

function r=bisection(f,a,b,tol,nmax)
% function r=bisection(f,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

上面是我的bisection方法代码。我对为什么该代码无法正常工作感到困惑。运行f(c)的结果每3次重复一次。谁能告诉我为什么此代码不起作用?

解决方法

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

function r=bisection(f,a,b,tol,nmax)
% function r=bisection(f,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,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。