Monday, August 2, 2021

Roots Finding: Open Methods

Here are the M-files provided to implement the Newton-Raphson, secant & modified secant method. 

Newton-Raphson M-file

function [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,varargin)
% newtraph: Newton-Raphson root location zeroes
% [root,ea,iter]=newtraph(func,dfunc,xr,es,maxit,p1,p2,...):
%   uses Newton-Raphson method to find the root of func
% input:
%   func = name of function
%   dfunc = name of derivative of function
%   xr = initial guess
%   es = desired relative error (default = 0.0001%)
%   maxit = maximum allowable iterations (default = 50)
%   p1,p2,... = additional parameters used by function
% output:
%   root = real root
%   ea = approximate relative error (%)
%   iter = number of iterations

if nargin<3,error('at least 3 input arguments required'),end
if nargin<4|isempty(es),es=0.0001;end
if nargin<5|isempty(maxit),maxit=50;end
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;

Secant M-file

function root = secant(func,xrold,xr,es,maxit)
% secant(func,xrold,xr,es,maxit):
% uses secant method to find the root of a function
% input:
%  func = name of function
%  xrold, xr = initial guesses
%  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

% Secant method
iter = 0;
while (1)
xrn = xr - func(xr)*(xrold - xr)/(func(xrold) - func(xr));
iter = iter + 1;
if xrn ~= 0, ea = abs((xrn - xr)/xrn)*100; end
if ea <= es | iter >= maxit, break, end
xrold = xr;
xr = xrn;
end
root = xrn;

Modified Secant M-file

function root = modsec(func,xr,delta,es,maxit)
% secant(func,xrold,xr,es,maxit):
% uses the modified secant method
% to find the root of a function
% input:
%  func = name of function
%  xr = initial guess
%  delta = perturbation fraction
%  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
if nargin<3, delta=1E-5; end %if delta blank set to 0.00001

% Secant method
iter = 0;
while (1)
xrold = xr;
xr = xr - delta*xr*func(xr)/(func(xr+delta*xr)-func(xr));
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr)*100; end
if ea <= es | iter >= maxit, break, end
end
root = xr;

No comments:

Post a Comment

Numerical Integration Formulas

Here are the M-files to implement composite trapezoidal rule for equally spaced data and unequally spaced data.  Composite Trapezoidal Rule ...