% log2_series.m
%
%  log(2) = 1 - 1/2 + 1/3 - 1/4 + 1/5 - ...
%  An alternating series with decreasing terms can be approximated
%  by adding up just the first M terms, with an error whose size is
%  no greater than term M+1.
%
acc = 0.000001;
estimate = 0.0;
n = 1;
s = 1;
a = 1;

while ( acc < abs ( a ) )
  estimate = estimate + a;
  n = n + 1;
  if ( mod ( n, 2 ) == 1 )
    a = 1 / n;
  else
    a = - 1 / n;
  end
end

fprintf ( '  %d terms were used\n', n );
fprintf ( '  Estimate for log(2) = %16.10f\n', estimate );
fprintf ( '  Exact value of log(2) = %16.10f\n', log ( 2.0 ) );
fprintf ( '  Overestimate of error = %16.10e\n', a );
fprintf ( '  Exact error = %16.10e\n', log ( 2.0 ) - estimate );
