function main() % File to show how to use bisection and Newton's method % (all in one script file). (Scroll down to see the functions) xb=bisect(@testfunc01,0,1,1e-9) xc=NewtonMethod(@testfunc01,0,20,1e-9) end % Functions defined below: function [y,dy]=testfunc01(x) % Test function e^x-3x y=exp(x)-3*x; % Output y dy=exp(x)-3; % and dy end function xc=bisect(f,a,b,tol) % Bisection Method, xc=bisect(f,a,b,tol) % Computes an approximation to f(x)=0 given that the % root is bracketed in [a,b] with f(a)f(b)<0. Will run % until TOL is reached, and will output the solution xc. % % EXAMPLE: f=inline('x^3+x-1'); % xc=bisect(f,0,1,0.00005); %Error check and initialization: fa=feval(f,a); fb=feval(f,b); if sign(fa)*sign(fb)>=0 error('Root may not be bracketed'); end iter=0; while (b-a)/2>tol iter=iter+1; c=(a+b)/2; fc=feval(f,c); if fc==0 %This means that (a+b)/2 is the root- break %Break out of the while loop and %continue execution end if sign(fc)*sign(fa)<0 %New interval is [a,c] (reset b) b=c; fb=fc; else a=c; fa=fc; %New interval is [c,b] (reset a) end end fprintf('Finished after %d iterates\n',iter); xc=(a+b)/2; end function out=NewtonMethod(F,x0,numits,tol) % Inputs to Newton's Method: % F- Name of a function that returns BOTH % values of g(x) and g'(x) % x0= Initial value of x. % numits= Maximum number of iterations % tol = Tolerance (like 1e-6) measures % change between iterates of x % % Example: % function [y,dy]=F(x) % y=x^2 - x - 1; % dy=2*x-1 % % out=NewtonMethod(F,1,10,1e-8) % for k=1:numits [g,dg]=feval(F,x0); if dg==0 error('Derivative is zero'); end xnew=x0-g/dg; d=abs(xnew-x0); if d