Simple Ruby Monte Carlo simulation

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. (Pretty boring, I know, but hey, I was bored, interested in learning Ruby, and didn't feel like reading any more of The Stand right now.)

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.

Post new comment

The content of this field is kept private and will not be shown publicly.