Professor Diomar Cesar Lobao

Universidade Federal Fluminense-Volta Redonda, RJ, Brasil

Diomar Cesar


Dept. Ciências Exatas - Exact Science Dept.

Search

secant.m

% Root finding using Secant method
%
% The function is defined in another script file as follows:
% (Note that this won't accept vector inputs)
%
%   function y = fcn(x)
%       y = x^4 - 5*x^3 - 124*x^2 + 380*x + 1200;
clear; clf; 

% First, plot the function to estimate the root location
fplot('fcn',[1 20])
hold on

% now proceed with finding a root:

x1 = input('Enter first guess of root location: ');
x2 = input('Enter second guess of root location: ');

itermax = 100;      % max # of iterations
iter = 0;
errmax = 0.001;     % convergence tolerance
error = 1;
fprintf('\n   #      x1        x2       x3       rel error\n\n');

while error > errmax & iter < itermax

  iter = iter + 1;
  f1 = fcn(x1);
  f2 = fcn(x2);

  x3 = x2 - f2*(x2-x1) / (f2 - f1);    % here is new root estimate
  plot(x3, fcn(x3),'ro')

  error = abs((x3 - x2)/x3) * 100;  % find change from previous

  fprintf('%3i %8g  %8g  %10.6f   %10.5f\n',iter,x1,x2,x3,error);
  x1 = x2;      % set up for next iteration
  x2 = x3;
end


Skip to content