Problem 5 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.)

Draw a grid of 1" squares on a table, then toss a penny (diameter 3/4") onto it. What's the probability the penny doesn't cross any line on the table? (Now, turn this into a carnival game and make some money.)
```#!/usr/bin/env ruby TRIALS=10000 # The goal in this one is to determine the probability # that the coin is inside the square. We can model # this one of two ways: the probability of crossing # a line, or the probability of not crossing any lines. # # P(crossing a line) is pretty hard, with four different # cases to consider (unless you model the grid in a # slightly inside-out way. After going through the below, # think of how you could rework the setup to model crossing # either line in the same manner.) # # Instead, we model the problem as # P(not crossing a line) # # We model the coin as a point (x,y), with a circle # drawn 3/8" around it, yielding a diameter of 3/4". # # Thus, to win, you must have x and y in the # range [3/8,5/8]. # RANGE_LOW = 3.0/8.0 RANGE_HIGH = 5.0/8.0 def win() x = rand() y = rand() return ( (x > RANGE_LOW) && (x < RANGE_HIGH) && (y > RANGE_LOW) && (y < RANGE_HIGH) ) end wins = 0 TRIALS.times { wins +=1 if win() } puts "Out of #{TRIALS} coin tosses, we won #{wins}." puts "The probability of winning is approximately #{wins.to_f/TRIALS.to_f}" ```

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.