Problem 43 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 43: A bar is broken at random in two places. Find the average length of the shortest, middle-est, and longest pieces.
#!/usr/bin/env ruby
TRIALS=100000
# Much like 42, this is pretty trivial stuff.
cum_short = 0.0
cum_med = 0.0
cum_long = 0.0
TRIALS.times {
b1 = rand()
b2 = rand()
# put them on a stick reasonably...
if (b1 > b2)
x = b1
b1 = b2
b2 = x
end
ls = [b1, b2-b1, 1.0-b2].sort
cum_short += ls[0]
cum_med += ls[1]
cum_long += ls[2]
}
m_short = cum_short/TRIALS
m_med = cum_med/TRIALS
m_long = cum_long/TRIALS
puts "After #{TRIALS} trials, average lengths:"
puts " #{m_short}, #{m_med}, #{m_long}"
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.