5 ms·
It may be a useful sanity check to simulate the experiment multiple times to see the result: def choose_coin rand < 0.001 ? 1 : 0.5 end def flip_
by mag487 13y ago
It may be a useful sanity check to simulate the experiment multiple times to see the result:
def choose_coin
rand < 0.001 ? 1 : 0.5
end
def flip_coin(coin)
rand < coin ? :heads : :tails
end
def all_10_heads?(coin)
10.times { return false if flip_coin(coin) == :tails }
true
end
next_flip = { :heads => 0, :tails => 0 }
1000000.times do
coin = choose_coin
next unless all_10_heads? coin
next_flip[flip_coin(coin)] += 1
end
puts next_flip[:heads].to_f / (next_flip[:heads] + next_flip[:tails])
- jules 13y agoWhat's really interesting is that there are probabilistic programming languages where you can write a program that does a simulation just like you did, but the execution engine can compute the probabilities exactly and much faster too. It does this by computing along all possible paths in the program, and keeping track of the probability mass of each path, and then summing them all up in the end. http://en.wikipedia.org/wiki/Probabilistic_programming_language http://en.wikipedia.org/wiki/Probabilistic_programming_langu...
- crntaylor 13y agoCompletely shameless plug for a tiny probabilistic programming language that I wrote as an embedded DSL in Haskell: https://github.com/chris-taylor/hs-probability https://github.com/chris-taylor/hs-probability The code that solves this problem is: solve = do coin <- choose (999/1000) fair biased tosses <- replicateM 10 coin condition (tosses == replicate 10 Head) nextToss <- coin return nextToss where fair = choose (1/2) Head Tail biased = certainly Head