function p = monte_carlo_pi( n )
  %---------------------------------------------------------------------------
  % Jonathan R. Senning <jonathan.senning@gordon.edu>
  % Gordon College
  % Written February 15, 2005
  %
  % $Id: monte_carlo_pi.m,v 1.2 2005/03/22 13:16:53 senning Exp senning $
  %
  % Usage: p = monte_carlo_pi( n )
  %
  % Returns:
  %       Estimate of pi computed with n trials.
  %
  % Parameter:
  %       n:      number of trials ("dart throws at unit square")
  %
  % This is based on a description in an introduction to Monte-Carlo methods
  % found at http://www.chem.unl.edu/zeng/joy/mclab/mcintro.html.  The idea
  % is to estimate pi by noting that the area of a quarter of a unit circle is
  % pi/4 and that if n darts are thrown randomly into a unit square the
  % fraction of them that land in a quarter of a unit circle is equal to the
  % fraction of the square area taken up by the quarter of the unit circle.
  %
  % |******--------------
  % |       ****  "miss"|
  % |            **     |
  % |               *   |
  % |                *  |
  % |  "hit"          * |
  % |                 * |
  % |                  *|
  % |__________________*|
  %
  %---------------------------------------------------------------------------

  x = rand( n, 1 );
  y = rand( n, 1 );

  % Here is an explanation of the calculation which follows:
  %  a = sqrt( x.^2 + y.^2 )         Computes the array of distance values
  %  b = 1 - sign( a )	           2 if distance is less than 1,
  %                                         0 if distance is greater than 1
  %  c = sum( 1 - sign( b ) ) / 2    Number of "hits"
  %  4 * ( c ) / n                   Estimate of pi.

  p = 4 * ( sum( 1 - sign( sqrt( x.^2 + y.^2 ) - 1 ) ) / 2 ) / n;

end
