function kelvin ( )

%*****************************************************************************80
%
%% KELVIN looks at Kelvin's fair results from a biased coin.
%
%  Discussion:
%
%    A biased coin comes up head with probability p.
%    To get a unbiased random value, toss the coin twice.
%    If you get TH, call it heads; if you get HT, call it tails.
%    If you get TT or HH, do another double toss.
%    On average, how many double tosses are necessary?
%
%  Example:
%
%     10,000 trials, average number of double tosses is 2.085.
%
%  Modified:
%
%    28 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'KELVIN:\n' );
  fprintf ( 1, '  A biased coin comes up head with probability p.\n' );
  fprintf ( 1, '  To get a unbiased random value, toss the coin twice.\n' );
  fprintf ( 1, '  If you get TH, call it heads; if you get HT, call it tails.\n' );
  fprintf ( 1, '  If you get TT or HH, do another double toss.\n' );
  fprintf ( 1, '  On average, how many double tosses are necessary?\n' );

  p = 0.4;
  total_number_of_double_tosses = 0;
  for loop = 1 : 10000

    number_of_double_tosses = 0;
    decision = 0;

    while ( decision == 0 )

      if ( rand ( ) < p )
        toss1 = 1;
      else
        toss1 = 0;
      end
      if ( rand ( ) < p )
        toss2 = 1;
      else
        toss2 = 0;
      end

      number_of_double_tosses = number_of_double_tosses + 1;

      if ( toss1 + toss2 == 1 )
        decision = 1;
      end    

    end

    total_number_of_double_tosses = total_number_of_double_tosses ...
      + number_of_double_tosses;

  end

  total_number_of_double_tosses = total_number_of_double_tosses / 10000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of double tosses = %g\n', ...
    total_number_of_double_tosses );
  fprintf ( 1, '  Theoretical value               = %g\n', 1 / 0.48 );

  return
end
