function paths ( )

#*****************************************************************************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 GNU LGPL license.
#
#  Modified:
#
#    08 February 2023
#
#  Author:
#
#    Original MATLAB version by Paul Nahin.
#    This version by John Burkardt.
#
#  Reference:
#
#    Paul Nahin,
#    Dueling Idiots and Other Probability Puzzlers,
#    Princeton, 2012,
#    ISBN: 978-0691155005.
#
  print ( '' )
  print ( 'paths():' )
  print ( '  Estimate the distribution and density functions' )
  print ( '  of the random variable L denoting random path lengths' )
  print ( '  across a unit square.' )
  print ( '' )
  print ( '  Report results graphically.' )

  length = zeros(1,142)

  for n = 1 : 100000

    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=.01:.01:1.42

  subplot ( 1, 2, 1 )
  plot ( x, length/1000 )
  grid ( 'on' )
  xlabel ( 'length' )
  ylabel ( 'magnitude' )
  title ( 'Density of L from 100,000 Paths' )

  subplot ( 1, 2, 2 )
  dist(1) = length(1)
  for index = 2:142
    dist(index) = dist(index-1)+length(index)

  plot ( x, dist/100000 )
  grid ( 'on' )
  xlabel ( 'length' )
  ylabel ( 'probability' )
  title ( 'Distribution of L from 100,000 Paths' )
  filename = 'paths.png'
  plt.savefig ( filename )
  print ( '  Graphics saved as "' + filename + '"' )
  plt.close ( )

  return
end
