Coin Flipping¶
Faisal Qureshi
faisal.qureshi@ontariotechu.ca
http://www.vclab.ca
Copyright information¶
© Faisal Qureshi
License¶
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.In [1]:
import numpy as np
import matplotlib.pyplot as plt
In [12]:
def coin_flips(num_flips):
'''Returns fraction of heads seen in num_flips coin flips. Also returns the count.'''
heads = float(np.sum(np.random.random((1, num_flips)) > 0.5))
return heads / num_flips, heads
In [18]:
def coin_flip_trials(num_trials, flips_per_trial):
'''Returns list of fraction of heads observed in num_flips coin flips at each trial.
Also returns counts.'''
heads_fractions = []
heads_counts = []
for i in range(num_trials):
fraction, count = coin_flips(flips_per_trial)
heads_fractions.append(fraction)
heads_counts.append(count)
return heads_fractions, heads_counts
In [20]:
num_trials = 2
flips_per_trial = 9
heads, counts = coin_flip_trials(num_trials=num_trials, flips_per_trial=flips_per_trial)
print('Coin flip trials:')
print(f'Num trials = {num_trials}')
print(f'Flips per trial = {flips_per_trial}')
print(f'Fraction of heads = {heads}, counts = {counts}')
Coin flip trials: Num trials = 2 Flips per trial = 9 Fraction of heads = [0.1111111111111111, 0.4444444444444444], counts = [1.0, 4.0]
Sampling to estimate probabilities¶
Q. What's the probability of not getting any head in $x$ coin flips?
In [35]:
x = 3
num_samples = 100000
success = 0
for i in range(num_samples):
_, counts = coin_flips(num_flips=x)
if counts == 0:
success = success + 1
print ('Probability of not getting a head in 10 coin flips: ', success/num_samples)
Probability of not getting a head in 10 coin flips: 0.12325
In [ ]: