function stirling3 ( )

%*****************************************************************************80
%
%% stirling3() compares n! and Stirling's approximation. 
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    30 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'stirling3():\n' );
  fprintf ( 1, '  Compare n! and Stirling''s approximation.\n' );
  fprintf ( 1, '  Present the results graphically.\n' );

  for n = 1 : 150
    f(n) = gamma ( n + 1 );
    s(n) = sqrt ( 2 * pi * n ) * ( n ^ 50 ) * exp ( -n ) * ( n ^ ( n - 50 ) );
%   s(n) = sqrt ( 2 * pi * n ) * ( n ^ n ) * exp ( - n );
  end
%
%  Graphics.
%
  clf ( );

  subplot ( 1, 2, 1 );
  semilogy ( f - s, 'linewidth', 3 );
  grid ( 'on' );
  xlabel ( 'n' );
  ylabel ( 'Absolute Error' );
  title ( 'n! - sqrt(2pi*n)(n^n)e^-n' );

  subplot ( 1, 2, 2 );
  plot ( f ./ s, 'linewidth', 3 );
  grid ( 'on' );
  xlabel ( 'n' );
  ylabel ( 'Relative Error' );
  title ( 'n! / [sqrt(2pi*n)(n^n)e^-n]' );

  filename = 'stirling3.png';
  print ( '-dpng', filename );
  fprintf ( '  Graphics saved as "%s"\n', filename );

  return
end
