% Matlab/octave for convergence of a series. M56, Lec 1. Barnett 3/26/13

format long g                      % makes show lots of (ie 16) digits

% algebraic..................
for n=10.^[3:9]
  s=0;
  for i=1:n, s = s+1/i^2; end
  [n, s]
end

y = pi^2/6;                        % exact, zeta(2)
abs(s-y)
% error is 9e-9. sum series other way, get 1e-9, which is the correct tail.


% Taylor exp for log(1-x), exponential conv...............
x = 0.7;
sn = [];                           % empty list for saving data
for n=10:10:100
  s=0;
  for i=1:n, s = s + x^i/i; end
  fprintf('n = %d : \t s_n = %.15g\n', n, s)   % nicer printing
  sn = [sn s];                     % save the data by appending to list
end
s + log(1-x)
y = s; % can use last s as exact y, since converged to all 15 digits

% plot the saved data (how could you prevent having to type 10:10:100 again?)
semilogy(10:10:100,abs(sn-y),'+-'); xlabel('n'); ylabel('error');

