如何在我的二等分代码中显示所有中点? [英] How to show all the midpoints on my bisection code?

查看:114
本文介绍了如何在我的二等分代码中显示所有中点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码可用于查找二等分(它终于可以工作了!),但是我还需要再添加3件事:

I have a code for finding the bisection (and it finally works!), but I need to include 3 more things:

  • output-根历史记录包含通过算法获得的中点序列的向量
  • 输出-函数的绝对值
  • f(x)在r处,即fRoot = f(r)输入-最大迭代次数

  • output- Root History a vector containing the sequence of midpoints obtained by the algorithm
  • output- the absolute value of the function
  • f(x) at r, i.e., fRoot = f(r) input- max iterations

function [R, E] = myBisection(f, a, b, tol)
    m = (a + b)/2;
    R = m;
    E = abs(f(m));
    while E(end) > tol
        if sign(f(a)) == sign(f(m))
            a = m;
        else
            b = m;
        end
        m = (a + b)/2;
        R = [R, m];
        E = [E, abs(f(m))];
    end

我该怎么做?谢谢!

推荐答案

我已纠正了缩进,您可以看到您已从函数末尾省略了end. (这是可选的,但最好不要遗漏这些内容,这样您就知道您并不是故意在最后写几行,但您忘记了.)

I have corrected indents an you can see that you've left out end from the end of the function. (it is optional but best not to leave those things out so you know you did not mean to write couple lines to the end but you forgot it.)

RE,如果您恰当地调用myBisection,那就是

R and E should be returned now, if you call myBisection apropriately, that is

[R, E] = myBisection(f, a, b, tol);

如果您只是打电话

myBisection(f, a, b, tol)

它只会返回R.

要增加迭代次数的限制,请更改while的条件,如下所示:

To add a limit on the number of iterations, you change while's condition like so:

iter=0;
while (E(end) > tol) && (iter<max_iter)
    iter = iter+1;
    % ...

end

或者最好在for循环中使用ifbreak:

or it is better to do it in a for loop, with an if plus break:

for iter=1:max_iter
    if(E(end) <= tol), break, end;
    % ...
end

这篇关于如何在我的二等分代码中显示所有中点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆