function stirling2 ( )

%*****************************************************************************80
%
%% STIRLING2 compares n! to Stirling's approximation.
%
%  Discussion:
%
%    Stirling approximates n! by sqrt(2*pi*n) * n^n * exp(-n).
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'STIRLING2\n' );
  fprintf ( 1, '  Stirling approximates n! by sqrt(2*pi*n) * n^n * exp(-n).\n' );
  fprintf ( 1, '  Display a plot of absolute and relative errors.\n' );

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

  subplot(1,2,1)
  semilogy ( f - s )
  grid
  xlabel('n')
  ylabel('Absolute Error')
  title('n! - [n^ne^-^n]')

  subplot(1,2,2)
  plot ( f ./ s )
  grid
  xlabel('n')
  ylabel('Relative Error')
  title('n!/[n^ne^-^n]')

  print ( '-dpng', 'stirling2.png' )

  return
end
