Professor Diomar Cesar Lobao

Universidade Federal Fluminense-Volta Redonda, RJ, Brasil

Diomar Cesar


Dept. Ciências Exatas - Exact Science Dept.

Search

incsrch.m

% root finding by incremental search
%
% This uses the external function func1.m defined as follows
%
%      function f = func1(x)
%         f = (x-4)*(x-10)*(x-20) + 1;
%
% This has roots near x = 4, 10, 20

clear

% get a quick plot of the function
xp = linspace(0,25);
yp = func1(xp);
plot(xp,yp)


x = input('Enter starting x value :');
xinc = input('Enter x increment :');
eps = input('Enter desired absolute accuracy :');

false = 0;
true = 1;

found = false;

while found == false
   xup = x + xinc;
   flow = func1(x);
   fup = func1(xup);
   
   if flow == 0 | fup == 0
      found = true;
   elseif flow*fup < 0
      fprintf('root between %g and %g\n',x,xup)
      if xinc < eps
         found = true;
      else
         xinc = xinc / 10;
         fprintf('Changing increment to %g\n\n',xinc)
      end
   else
      x = xup;
   end
end
   
x
flow
xup
fup
Skip to content