function even = 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
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  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
%
%  Input:
%
%    integer N, the number of flips.
%
%    real P, the probability of heads on one toss.
%
%  Output:
%
%    real EVEN: the probability of an even number of heads.
%
  trial_num = 100000;

  even = 0;

  for loop1 = 1 : trial_num
    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 / trial_num;

  return
end
