function flips ( n, p )

%*****************************************************************************80
%
%% FLIPS estimates chances of an even number of heads in N coin flips.
%
%  Discussion:
%
%    A biased coin has probability P of heads.
%    The coin is tossed N times.
%    What is the probability of an even number of heads?
%
%  Examples:
%
%    N    P   Exact
%
%    9  0.1  0.5671
%    9  0.9  0.4329
%
%  Modified:
%
%    01 February 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Will You Be Alive 10 Years From Now?,
%    Princeton, 2014,
%    ISBN: 978-0691156804,
%    LC: QA273.25.N344
%
%  Parameters:
%
%    Input, integer N, the number of flips.
%
%    Input, real P, the probability of heads on one toss.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'FLIPS:\n' );
  fprintf ( 1, '  A biased coin has probability P of heads.\n' );
  fprintf ( 1, '  The coin is tossed N times.\n' );
  fprintf ( 1, '  What is the probability of an even number of heads?\n' );

  even = 0;
  for loop1 = 1 : 1000000
    for loop2 = 1 : n
      result = rand ( );
      if ( result < p )
        f(loop2) = 1;
      else
        f(loop2) = 0;
      end
    end
    total = sum ( f );
    if ( mod ( total, 2 ) == 0 )
      even = even + 1;
    end
  end

  even = even / 1000000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of tosses = %d\n', n );
  fprintf ( 1, '  Probability of heads = %g\n', p );
  fprintf ( 1, '  Probability of even number of heads = %g\n', even );

  return
end
