function randomsum ( )

%*****************************************************************************80
%
%% RANDOMSUM carries out a process that estimates E.
%
%  Discussion:
%
%    Add a sequence of random values until you exceed 1.
%    Let N be the number of terms in this sequence.
%    Repeating this process M times, let D(N) be the number of times
%    that N terms were required.
%    Then E can be approximated by 1*D(1) + 2*D(2) + ... * I * D(I) + ...
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'RANDOMSUM:\n' );
  fprintf ( 1, '  Add a sequence of random values until you exceed 1.\n' );
  fprintf ( 1, '  Let N be the number of terms in this sequence.\n' );
  fprintf ( 1, '  Repeating this process M times, let D(N) be the number of times\n' );
  fprintf ( 1, '  that N terms were required.\n' );
  fprintf ( 1, '  Then E can be approximated by 1*D(1) + 2*D(2) + ... * I * D(I) + ...\n' );

  d = zeros ( 1, 20 );
  k = 1;

  while ( k <= 100000 )

    n = 0;
    summation = 0;
    while ( summation < 1 ) 
      summation = summation + rand ( );
      n = n + 1;
    end

    d(n) = d(n) + 1;
    k = k + 1;

  end

  e = 0;
  for n = 1 : 20
    e = e + n * d(n);
  end

  e = e / 100000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimate for E = %g\n', e );
  fprintf ( 1, '  Exact value =    %g\n', exp ( 1 ) );

  return
end
                                              
