Problem 42 of Monte Carlo solutions to Fifty Challenging Problems...

(This is another part of the Fifty Problems series, a set of example applications of Monte Carlo methods. In each post, I present source code which answers a probabilistic question using simulated models of the underlying system.)

Problem 42: If a stick is broken in two at random, what is the average length of the shorter half? What is the average ratio of the shorter side to the longer side?
#!/usr/bin/env ruby

TRIALS = 1000000

# This is pretty trivial: we just choose a breakpoint somewhere
# along a unit-length stick and keep track of the total
# length of the short ends, and the ratio for (b)

cum_short_len = 0.0
cum_ratio = 0.0

TRIALS.times {
  breakpoint = rand()
  breakpoint = 1.0 - breakpoint if breakpoint > 0.5
  cum_short_len += breakpoint

  cum_ratio += breakpoint / (1.0 - breakpoint)

mean = cum_short_len / TRIALS
mean_ratio = cum_ratio / TRIALS

puts "After #{TRIALS} attempts, mean(short_len) = #{mean}"
puts "   mean(ratio) = #{mean_ratio}"

I've been coding my way through Fifty Challenging Problems in Statistics with Solutions. This post is a part of the Fifty Challenging Problems series.

This was brought to you by Josh Myer. He has other fun things at his homepage.