Suppose you flip coins for a certain times, say
n
. You want to know your chance of getting certain number of heads in a row, say k
heads in a row.
Let's start with the function that'll do a certain number of coin flips:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def do_n_flips(n): | |
return ''.join([str(random.getrandbits(1)) for i in range(n)]) |
do_n_flips(10)
'0100111001'
Let's suppose you get 1 euro if you get the given number of heads in a row while doing a certain number of flips. Here's the function that'll calculate your payoff:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def payoff(n, k): | |
if do_n_flips(n).find(''.rjust(k, '0')) > -1: | |
return 1.0 | |
else: | |
return 0.0 | |
payoff(10, 3)
0.0
payoff(10, 3)
1.0
Now, what is your chance to get your 1 euro for 3 heads in a row from 10 flips? This brings us to the Monte Carlo simulation, which I'wont describe here at all, just give you a function which answers our question regarding the chance:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def monte_carlo_solve(n, k, j): | |
ret = 0.0 | |
for x in range(j): | |
ret = ret + payoff(n, k) | |
return ret / j |
monte_carlo_solve(10, 3, 1000000)
0.507753
This post was inspired by a similar post by Remis.