Professor Diomar Cesar Lobao

Universidade Federal Fluminense-Volta Redonda, RJ, Brasil

Diomar Cesar


Dept. Ciências Exatas - Exact Science Dept.

Search

onepoint.m

% Demonstration of One Point Iteration
clear; figure(1);clf;figure(2);clf;figure(1)

f = 'exp(-x)-x';       %define the function f(x)=0
g = 'exp(-x)';         %and a    x = g(x)   form

disp(['f(x) is ' f]); 
disp(['g(x) is ' g]);

% plot the function
xmax=3;
grange = [-xmax xmax];
figure(1); ezplot(f,grange); hold on; line (grange, [0 0]); pause

% have a look at the g(x) function
figure(2); ezplot(g,[-1 xmax]); 
hold on
plot([-1 xmax], [-1 xmax],'g')  % line defines x = x


x = input ('Enter initial guess of root:        ');
if length(x)==0;x=0;end
maxerror = 0.1; % maximum error
   maxit = 30;  % maximum number of iterations
   count = 0;   % iteration counter
   error = 1;   % starting error (100 percent)

fprintf('\n Iteration      x       g(x)     error(%%)    f(x)\n\n');


% this is where all the work gets done.....
while (error > maxerror) & (count < maxit)
  count = count + 1;
  xnew = eval(g);
  error = abs((xnew - x)/xnew) * 100;
  fprintf('%7g %10.4f %10.4f %10.4f  %10.4f\n',count,x,xnew,error,eval(f));
  
  %these 2 lines are added just to show the convergence graphically
  if count>1;line([x x],[x xnew]);else;plot(x,eval(g),'r*');end
  line([x xnew],[xnew xnew]);pause
  
  x = xnew;
end

if count<maxit
   fprintf('\nRoot is %g   Function at root is %g\n',x,eval(f))
   figure(1);plot(x,eval(f),'ro')
   figure(2);plot(x,eval(g),'ro')       % circle at root found
end

Skip to content