Solution
You can use uniofrom distribution \( [0,1] \) to solve this problem.
- First, Generate a random number between 0 and 1 using a uniform distribution. This random number represents the outcome of a fair coin flip.
-
Compare this random number with the probability of getting heads \(p\). If the random number is less than \(p\), you consider it as a head. Otherwise, it's a tail.
import numpy as np
def coin_toss(probability_of_head, number_of_trails):
"""
Function to simulate coin toss
Args:
probability_of_head: this indicate whether coin is biassed or unbiassed
number_of_trails: number of time experiment to be run
Return:
list which contains output of each trail
"""
output_list = []
if probability_of_head < 0 or probability_of_head > 1:
return -1
if number_of_trails < 0:
return -1
for i in range(number_of_trails):
random_number = np.random.rand()
if random_number<= probability_of_head:
output_list.append(1)
else:
output_list.append(0)
return output_list