Single point Bisection Method - f(x)=e^(-x) -x

65 Views Asked by At

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?

1

There are 1 best solutions below

2
Ander Biguri On

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