% CP5p2.m
% Root finding using fix-point iterations.
% K. Ming Leung, 03/20/04

clear all; 

% Define the 4 fixed-point functions using inline:
g1 = inline('(x.*x+2)/3');
g2 = inline('sqrt(3*x-2)');
g3 = inline('3-2./x');
g4 = inline('(x.*x-2)./(2*x-3)');

% Plot the 4 fixed-point iteration functions:
% (No need to do for the homework)
limx = 3; xx=[0 limx]; yy=[0 limx];
x1 = eps:0.02:limx; x2=1.5:0.02:limx; x3=0.5:0.02:limx; x4=0:0.02:limx;
subplot(2,2,1); 
plot(x1,feval(g1,x1),'b-',xx,yy,'r-');
ylabel('g_1(x)'); xlabel('x');
subplot(2,2,2); 
plot(x2,feval(g2,x2),'b-',xx,yy,'r-');
ylabel('g_2(x)'); xlabel('x');
subplot(2,2,3); 
plot(x3,feval(g3,x3),'b-',xx,yy,'r-');
ylabel('g_3(x)'); xlabel('x');
subplot(2,2,4); 
plot(x4,feval(g4,x4),'b-',xx,yy,'r-');
ylabel('g_4(x)'); xlabel('x');

exact = 2;  % Exact root:
x = 4;      % Starting guess:

% Specify the maximum number of iterations:
maxIt = 12;  % for g1
% maxIt = 27;  % for g2
% maxIt = 15;  % for g3
% maxIt = 7;  % for g4

fprintf('iteration          x                       error\n');
fprintf('=========================================================\n');

for iteration = 1:maxIt
    x = feval(g1,x);
    fprintf('%5i %25.14e % 25.14e\n',iteration,x,x-exact);
end


