%
% Sum a series for pi until it has better accuracy than 22/7.
%
%  Reference:
%
%    John D Cook,
%    Asimov's question about pi,
%    https://www.johndcook.com/blog/
%    4 September 2019
%
%    Isaac Asimov,
%    Asimov on Numbers,
%    1977
%    
  x1 = pi;
  x2 = 22.0 / 7.0;
  e2 = abs ( x1 - x2 );
%
%  Sum terms until error is less than e.
%
  k = 0;
  s = 1.0;
  x3 = 0.0;
  while ( true )
    k = k + 1;
    t = s * 4.0 / ( 2 * k - 1 );
    x3 = x3 + t;
    e3 = abs ( x1 - x3 );
    if ( e3 <= e2 )
      break;
    end
    s = - s;
  end

  fprintf ( 1, '  Pi     = %20.16g\n', x1 );
  fprintf ( 1, '  22/7   = %20.16g, ||Pi-22/7||   = %e\n', x2, e2 );
  fprintf ( 1, '  Series = %20.16g, ||Pi-Series|| = %e, using %d terms\n', ...
    x3, e3, k );

