Search code examples
pythondistributioncoin-flipping

Tossing a fair coin for 100 times and count the number of heads. Repeat this simulation 10**5 times


Write a program to simulate tossing a fair coin for 100 times and count the number of heads. Repeat this simulation 10**5 times to obtain a distribution of the head count.

I wrote below code to count number of heads 100 times, and outer loop should repeat my function 100K times to obtain distribution of the head:

import random
def coinToss():
    return random.randint(0, 1)

recordList = []

for j in range(10**5):

    for i in range(100):
        flip = coinToss()
        if (flip == 0):
            recordList.append(0)

    print(str(recordList.count(0)))

but each time I run my program, instead of getting a list of 100K heads probability, I get no#s higher, can anyone tell me what I doing wrong ?

42

89

136

....

392

442

491


Solution

  • Since the original problem asks for a distribution of head counts, you need to keep track of two lists: one for the number of heads per 100-toss trial, and one for the number of heads in the current 100-toss trial.

    import random
    def coinToss():
        return random.randint(0, 1)
    
    experiments = [] # Number of heads per 100-toss experiment
    
    for j in range(10**5):
        cnt = [] # Number of heads in current 100-toss experiment
        for i in range(100):
            flip = coinToss()
            if (flip == 0):
                cnt.append(0)
        experiments.append(cnt.count(0))
        print(str(cnt.count(0)))
    

    However, I would strongly suggest doing this in something like numpy which will greatly improve performance. You can do this is one line with numpy:

    import numpy as np
    experiments = np.random.binomial(n=100, p=0.5, size=10**5)
    

    You can then analyze/plot the distribution of head counts with whatever tools you want (e.g. numpy, matplotlib).