#Q26: Biased coin toss

Suppose you want to generate a sample of heads and tails from a fair coin. However, you only have a biased coin available (meaning the probability of coming up with heads is different than 1/2).

Write a simulation in Python that will use your biased coin to generate a sample of heads/tails as if it were coming from a fair coin.

TRY IT YOURSELF

ANSWER

This question is wordy but the task is straightforward, we need to code up a coin flip experiment in python where the chance of landing on one of heads or tails is not 0.5. This sounds difficult to do but let’s take advantage of Python’s random package.

The random package has a function random() which generates a number between 0 and 1. We can use this as a threshold to determine the weighting of our unfair coin for selecting heads or tails. This threshold can be written using if/else statements. Finally, to simulate a large number of events we can utilize a while loop (remember to make sure its not an infinite loop).

import randomi = 0 
heads = 0
tails = 0
while i < 10000:
i+=1 # Prevents infinite loop, += adds 1 to variable
num = random.random() #call the package and call function
if num < 0.2:
heads += 1
else:
tails += 1
print(heads)
print(tails)

--

--