Psmith
Psmith

Reputation: 43

Coin tossing simulation unexpected probabilities

This is a script I wrote to simulate a coin toss game that ends in a given fixed sequence of outcomes (tosses are either ones or zeroes). This fixed sequence characterizes the game. For example, coin_series('01') simulates a series of tosses that culminate in a 0 followed by a 1; valid outcomes are x01 where x is a string of zeroes and ones not containing the pattern 01 anywhere.

The script gives the number of throws required to terminate two games, 01 and 11, and these should have the same result since the coin is not a biased one (equal chance of outcome zero or outcome one on a toss).

Yet this is not the case, with my output being 6 and 4 respectively, of which only the first is correct. So I must have a bug in the script.

My questions are: how can I make the script a little more concise, as I hope this will help find the bug; and second, is there a bug that is apparent to all but me?

import numpy as np
class coin_series(object):
    def __init__(self,win_state):    #win_state is a string of ones and zeroes
        self.win_state=win_state
        self.d=self.draw()
        self.series=[self.d.next() for i in range(len(self.win_state))]
        self.n=len(self.win_state)
        while not self.check():
            self.play()
    def draw(self):
        while True:
            t=np.random.rand()
            if t>=0.5:
                yield 1
            else:
                yield 0
    def check(self):
        return(self.win_state==''.join(map(str,self.series)))
    def play(self):
        self.series=self.series[1:]+[self.d.next()]
        self.n+=1
if __name__=='__main__':
    print np.mean([coin_series('11').n for i in range(100000)])
    print np.mean([coin_series('01').n for i in range(100000)])

Upvotes: 1

Views: 119

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

This is no bug, your code works just fine!

As you toss the coins, if you are aiming for a 0 then a 1 and you make the 0 but the 1 ends up being another 0, then you are still already halfway there, you are just hoping for a 1 again.

On the other hand, if you are aiming for a 1 and then a 1 and make the 1, then if you don't make the second 1, you are now on a 0 and back to waiting for a first 1.

So to reword that a different way, in the first case, if you fail, you only get reset halfway, but in the second case, if you fail then you are back to the start again - thus increasing the average number of throws to get them.

Take a look at this redit post for another explanation.

Upvotes: 1

user2357112
user2357112

Reputation: 280698

No bug. You would need to be generating separate pairs of flips for those values to be equal. If you generate a continuous sequence of flips and look at overlapping pairs, 11 takes longer to come up on average than 01.

Upvotes: 1

Related Questions