A Ruby Monte Carlo simulation of coin flips

For some reason or another today I was curious about this question: If you flipped a coin ten times, what are the odds that the coin would come up heads ten times, or tails ten times)?

I'm sure there is a way to determine this statistically, but I don’t know how to do that, so, being new to Ruby, I wrote a little Ruby simulation program — essentially a Monte Carlo simulation of the problem — to find the answer.

Example Ruby “Monte Carlo simulation” program

Without any further ado, here is the example Ruby program I wrote to simulate this problem:

# my ruby random method, with an intentionally short name
def r
  rand(2)
end

# if all elements in the array "a" are the same, return true
def all_equal a
  a[0] == a[1] and 
  a[0] == a[2] and
  a[0] == a[3] and
  a[0] == a[4] and
  a[0] == a[5] and
  a[0] == a[6] and
  a[0] == a[7] and
  a[0] == a[8] and
  a[0] == a[9]
end

# out of the array, determine the number of elements that match "num"
def get_count arr, num
  count = 0
  arr.each do |a|
    if a == num then
      count = count + 1
    end
  end
  return count
end

#------#
# main #
#------#
num_all_equal = 0.0
num_heads = 0
num_tails = 0
tot_count = 250000
tot_count.times {
  flips = [r,r,r,r,r,r,r,r,r,r]
  #puts flips.inspect
  if all_equal(flips) then 
    num_all_equal = num_all_equal + 1
  end
  num_heads = num_heads + get_count(flips, 0)
  num_tails = num_tails + get_count(flips, 1)
}
pct_all_equal = num_all_equal/tot_count*100.0
puts "num where all were the same: #{num_all_equal}"
puts "all sides were equal #{pct_all_equal}% of the time"
puts "#heads: #{num_heads}"
puts "#tails: #{num_tails}"

It’s worth noting that my Ruby get_count method and the last few lines of the program are not necessary. I just put them in there to be sure I was getting a relatively even spread between heads (the number 0) and tails (the number 1) in my Monte Carlo simulation.

Finally, here is some example output from the program:

num where all were the same: 513.0
all sides were equal 0.2052% of the time
#heads: 1249227
#tails: 1250773

Of course the actual numbers change a little with each simulation, but that’s an example of the output I get with the simulation.

Comments

Permalink

Great! To give the formal side:

Pr[10 same] = Pr[10 heads] + Pr[10 tails]

Generally Pr[N heads] = Pr[heads]^N

So, assuming a fair toss, Pr[10 heads] = 0.5^10 = (approx) 0.001

Since Pr[heads] = Pr[tails],
Pr[10 same] = 2*(0.5^10) = (approx) 0.0019

To translate to your % result, across a given number of trials of 10 tosses each, we would expect about 0.195% to be successful.... About 488 of 250,000.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.