How to show all the midpoints on my bisection code?

半世苍凉 提交于 2020-01-07 04:28:23

问题


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

  • 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
    

how do I do this? thanks!!


回答1:


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.)

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

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

If you just call

myBisection(f, a, b, tol)

it will only return R.

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

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


来源:https://stackoverflow.com/questions/13459784/how-to-show-all-the-midpoints-on-my-bisection-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!