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
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?