% Sample program for the Lab Session 1 tasks
% ==========================================
%   
% 1. Compute the first 20 members of each of the sequences 

x(1) = 0;
y(1) = 1;
z(1) = 0;

for n = 1:19
  x(n+1) = cos(x(n));
  y(n+1) = 1 - cos(y(n));
  z(n+1) = z(n) + 1/n^2;
end

% 2. Plot sequence index vs. the log of the error
%
% First we have to know what the limits are.  In the case
% of x(n), there is no closed-form expression, so we simply iterate
% a few more times

xi = x(20);
for n = 1:10
  xi = cos(xi);
end

eta  = 0;
zeta = pi^2/6;

x_error = abs(x -   xi*ones(20,1));
y_error = abs(y -  eta*ones(20,1));
z_error = abs(z - zeta*ones(20,1));

nn = [1:20]; % Vector with the "x" coordinates for plotting 

semilogy(nn,x_error,nn,y_error,nn,z_error);

pause;

% 3. Perform a log-log plot of the k-th vs. the (k+1)-th error
%
% We also plot a line with slope 2 for comparison.  The plot will
% show that both lines have roughly the same slope, so y(n)
% does indeed converge with order 2.

y_error1=y_error(1:19);
y_error2=y_error(2:20);

y_line=exp(-2*nn);
x_line=exp(-nn);

loglog(y_error1,y_error2,x_line,y_line);

