Andy
Andy

Reputation: 225

Python coin-toss

i am new to Python, and i can't wrap my head around this. I have following function defined:

def FlipCoins(num_flips):
    heads_rounds_won = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
    return heads_rounds_won

Here is what it should do (but apparently doesn't): flip a coin num_flip times, count heads and tails, and see if there are more heads than tails. If yes, increment head_rounds_won by 1. Repeat 10000 times.

I would assume that head_rounds_won will approximate 5000 (50%). And it does that for odd numbers as input. For example, 3, 5 or 7 will produce about 50%. However, even numbers will produce much lower results, more like 34%. Small numbers especially, with higher even numbers, like for example 800, the difference to 50% is much narrower.

Why is this the case? Shouldn't any input produce about 50% heads/tails?

Upvotes: 2

Views: 4537

Answers (2)

mitch
mitch

Reputation: 1900

You just got a lot of rounds that are tied

def FlipCoins(num_flips):
    heads_rounds_won = 0
    tails_rounds_won = 0
    tied_rounds = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
        elif heads < tails: tails_rounds_won+= 1
        else: tied_rounds += 1
    return heads_rounds_won, tails_rounds_won, tied_rounds

will return something like

>>> FlipCoins(2)
(2506, 2503, 4991)

Upvotes: 9

kojiro
kojiro

Reputation: 77059

This is fun to watch and (eventually) demonstrates that randint(0,1) has a 50/50 probability of choosing 0 or 1. Community wiki since it's informative, but not a direct answer to the question.

s = [0, 0]
while True:
    an_int = randint(0, 1)
    s[an_int] += 1
    l = sum(s)
    print 'size: %d - %f%% zeros, %f%% ones' % (l, (100 * s[0]) / float(l), (100 * s[1]) / float(l))

Upvotes: 0

Related Questions