Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the given Matlab code for the bisection algorithm so that the outputs are

ID: 3888844 • Letter: M

Question

Modify the given Matlab code for the bisection algorithm so that the outputs are n, an, bn, pn=(an+bn)/2, f(pn) and bn-an. Stop the alorithm when abs(bn-an)<10-12 or after 45 iterations, whichever comes first.

function [root,iter,res] = bisection(fx,a,b,tol)

% Method of bisection.

if nargin < 4, tol = eps;

end

fa = fx(a); fb = fx(b); iter = 0;

while abs(a-b) > tol*max(abs(a),abs(b))

   mid = (a+b)/2; fmid = fx(mid);

   if fa*fmid<=0

% There is a root in [a,mid].

b = mid; fb = fmid;

   else

% There is a root in [mid,b].

a = mid; fa = fmid;

   end

   iter = iter + 1;

end

root = (a+b)/2;

res = fx(root);

So I'm assuming we can set tol=10-12 but I don't know how to check when I need to stop. I also am not sure how to modify the outputs/ inputs and how that would look. Any help greatly appreciated.

Explanation / Answer

function [root,iter,res] = bisection(fx,a,b,tol)

% Method of bisection.

if nargin < 4

    tol = eps;

end

fa = fx(a); fb = fx(b); iter = 0;

while abs(a-b) > tol*2

  mid = (a+b)/2; fmid = fx(mid);    

  if fa*fmid<=0   

     % There is a root in [a,mid].

     b = mid; fb = fmid;

  else

     % There is a root in [mid,b].

     a = mid; fa = fmid;

  end

  iter = iter + 1;

end

root = (a+b)/2;

res = fx(root);

end

I made minor change and it is working...

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote