% hw027.m
%
%  Estimate an infinite alternating series with decreasing terms.
%
%  S = 1/2 - 1/4 + 1/8 - 1/16 + ...
%
acc = input ( '  Enter desired accuracy: ' );
s_exact = 1/3;
s = 0.0;
a = 1/2;
n = 0;

while ( acc < abs ( a ) )

  n = n + 1;
  s = s + a;
  a = - a / 2.0;

end

fprintf ( '\n' );
fprintf ( '  Exact     S = %20.16f\n', s_exact ); 
fprintf ( '  Estimated S = %20.16f\n', s );  
fprintf ( '  Error       = %20.16f\n', abs ( s - s_exact ) );
fprintf ( '  Error est   = %20.16f\n', abs ( a ) );
fprintf ( '  Accuracy    = %20.16f\n', acc );
fprintf ( '  Number of terms = %d\n', n );
