1.
Bisection method
__________________________________________________
function root = bisection(func,xl,xu,es,maxit)
% root = bisection(func,xl,xu,es,maxit):
% uses bisection method to find the root of a function
% input:
% func = name of function
% xl, xu = lower and upper guesses
% es = (optional) stopping criterion (%)
% maxit = (optional) maximum allowable iterations
% output:
% root = real root
if func(xl)*func(xu)>0 %if guesses do not bracket a sign change
disp('no bracket') %display an error message
return %and terminate
end
% if necessary, assign default values
if nargin<5, maxit=50; end %if maxit blank set to 50
if nargin<4, es=0.001; end %if es blank set to 0.001
% bisection
iter = 0;
xr = xl;
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end
test = func(xl)*func(xr);
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
if ea <= es | iter >= maxit, break, end
end
root = xr;
______________________________________________________
2. Newton Raphson method
______________________________________________________
function root = newtraph(func,dfunc,xr,es,maxit)
% root = newtraph(func,dfunc,xguess,es,maxit):
% uses Newton-Raphson method to find the root of a function
% input:
% func = name of function
% dfunc = name of derivative of function
% xguess = initial guess
% es = (optional) stopping criterion (%)
% maxit = (optional) maximum allowable iterations
% output:
% root = real root
% if necessary, assign default values
if nargin<5, maxit=50; end %if maxit blank set to 50
if nargin<4, es=0.001; end %if es blank set to 0.001
% Newton-Raphson
iter = 0;
while (1)
xrold = xr;
xr = xr - func(xr)/dfunc(xr);
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr) * 100; end
if ea <= es | iter >= maxit, break, end
end
root = xr;