DEV Community

Cover image for Simulating the flip of a coin using python
Gauri Shanker
Gauri Shanker

Posted on

Simulating the flip of a coin using python

Recently I published a YouTube video in which I calculated the probability of a head on a coin flip. The catch here is that it is also to be demonstrated using a computer program simulating a coin flip for at least a million iterations. You can watch the video here -

Mathematically speaking, the probability of an event is calculated by the following formula -

Probability of an event = (Number of favorable events)/(Number of all possible events)(Number~of~favorable~events)/(Number~of~all~possible~events)

Here, in this scenario, the favorable event is the appearance of 'Head' and all possible events are any of the faces 'Heads or Tails'. Thus the number of favorable events is 1 whereas the number of all possible events is 2. Thus according to the formula of probability- we get a probability of 1/2 or 50% approx.

Well, now is the time to simulate that using python. Let's get moving -

First of all, import the random module because we have to randomly select a face of the coin.

import random 

Now, its time to create a function, we name it experiment. This function will simulate one coin flip and return 1 if we get a Head and 0 if we got a Tail.

def experiment(): faces = ['T', 'H'] # all possible faces  top_face = random.random(faces) # randomly choose a face  if top_face == 'H': # Checking if we got a head  return 1 # return 1 if success  return 0 # otherwise return 0 

Now that we have created our function, its time to test it for a million iterations -

headCounter = 0 # variable to count the number of times we get heads # conduct the experiment a million times and count the heads for _ in range(1000000): headCounter += experiment() # Print the results as percentage of total number of iterations print(f"The probability of getting head is {headCounter / 1000000 * 100}%") 

In my tests, I am consistently getting numbers close to 50 such as 50.0021% and 50.0017% which is in-line with our calculations.

Hope you enjoyed this article. You can also watch my YouTube video here on which this article is based.

Thanks and bye guys. I will see you in the next one.

Top comments (0)