function p2 = liar ( n, p1 )

%*****************************************************************************80
%
%% liar analyzes the liar problem.
%
%  Discussion:
%
%    A chain of N ocassional liars is created.
%
%    Each person lies with a probability p1.
%
%    Suppose a true statement is given to the first person, who
%    passes it on or, if lying, passes on its opposite, to the next.
%    What is the probability that a true statement will emerge as a
%    true statement at the end of the chain?
%
%  Modified:
%
%    07 May 2019
%
%  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 people in the chain.
%
%    Input, real p1, the probability that a given person will lie.
%
%    Output, real p2, the probability that an initial true statement will
%    emerge as a true statement at the end of the chain.
%
  trial_num = 10000000;
  total = 0.0;

  for game = 1 : trial_num

    lies = 0;
    for k = 1 : n
      if ( p1 < rand( ) )
        lies = lies + 1;
      end
    end

    if ( mod ( lies, 2 ) == 0 )
      total = total + 1;
    end

  end

  p2 = total / trial_num;

  return
end
