function paths ( trial_num )

%*****************************************************************************80
%
%% paths() estimates the length of the average walk across a square.
%
%  Discussion:
%
%    This code estimates the distribution and density functions
%    of the random variable L denoting random path lengths
%    across a unit square.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'paths():\n' );
  fprintf ( 1, '  Estimate the distribution and density functions\n' );
  fprintf ( 1, '  of the random variable L denoting random path lengths\n' );
  fprintf ( 1, '  across a unit square.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Report results graphically.\n' );

  length = zeros(1,142);

  for n = 1 : trial_num

    x = rand ( );
    angle = pi * rand ( );
    A1 = atan ( 1 / ( 1 - x ) );

    if ( angle < A1 )
      L = ( 1 - x ) / cos ( angle );
    elseif ( angle > A1 && angle < pi - atan ( 1 / x ) )
      L = 1 / sin ( angle );
    else
      L = - x / cos ( angle );
    end

    index = round ( 100 * L + 0.5 );
    length(index) = length(index) + 1;

  end
%
%  Graphics.
%
  clf ( );

  x = 0.01 : 0.01 : 1.42;

  subplot ( 1, 2, 1 );
  plot ( x, length/1000, 'linewidth', 3 );
  grid ( 'on' );
  xlabel ( 'length' );
  ylabel ( 'magnitude' );
  title ( 'Density of L Paths' );

  subplot ( 1, 2, 2 );
  dist(1) = length(1);
  for index = 2:142
     dist(index) = dist(index-1)+length(index);
  end
  plot ( x, dist/trial_num, 'linewidth', 3 );
  grid ( 'on' );
  xlabel ( 'length' );
  ylabel ( 'probability' );
  title ( 'Distribution of L' );

  filename = 'paths.png';
  print ( '-dpng', filename );
  fprintf ( '  Graphics saved as "%s"\n', filename );

  return
end
