1

I want to find the root of f(x)=e^(-x) -x using the bisection method for a single point. I Was given c = sgn f(a)(b − a) I will use this later on the main program and enter image description here

So first of all I have the following program in MATLAB:

function [y] =f(x)
  y=exp(-x)-x;
end

then for my sgn which is the wheather the f(x) is negative or positive:

function [z] =sgn(x)
  w=f(x);
  if (w>0)
      z=1;
    elseif(w==0)
      z=0;
    else
      z=-1;
  endif
end

So implementing these in my final program I have the following code:

function [root,i,e]=bisection_mod(a,b,tol)
  a=-1;b=2;

  i=0;
  xold= a;
  xnew=0;
  tol = 10^(-8);
  e = abs(xnew-xold);
  sgn(f(a))
  c=sgn(f(a))*(b-a)


  while (abs(xnew-xold) > tol)
           if (i>1)
             xold = xnew;
           endif
           cc=c*sgn(f(xold));
           par=(2^(i+1));
           xnew = xold + cc./par


           e = abs(xnew-xold)




       i=i+1;
       if (i>100)
          break
       endif
  endwhile
  i
  root=xnew
endfunction

the root of the function im trying to examin is 0.567 but my program gives back 0.2246.

Could I have some info about what I’m doing wrong or some corrections to my code?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Steve
  • 21
  • 2
  • As a curiosity: are you studying math? because this perhaps is the most contrived way to describe the bisection method, so it must have been written by a matematician. – Ander Biguri Nov 12 '22 at 15:43

1 Answers1

1

Just a couple of tiny mistakes:

Your sgn function is computing sgn(f(f(x)))! You give it f(x) as input, and the first thing you do inside is do f(x) again! remote it from inside the function, make w=x.

You are not updating xold for the first 2 iterations! The first skip is OK, but in the second iteration i==1, therefore the condition should read if (i>=1) or better if(i>0).

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • wow thank you very much! im kinda happy my code wasnt that much faulty and it was just me making a simple mistake. – Steve Nov 12 '22 at 14:26
  • @Steve that is 99% of code issue though! hehe. Its always the minus. Consider accepting the question as valid if it helped you, so future people can know that its the thing that worked for you. – Ander Biguri Nov 12 '22 at 14:48