In [8]:
from random import randint
class CoinTossTrials(object):
def __init__(self, n_flips, n_trials, coins_weighted, weight_heads):
"""
Arguments:
n_flips: the number of flips to perform in a trial
n_trials: the number of trials to perform in the experiment
coins_weighted: the percent of trials to use weighted coins
weight_heads: the probability that a weighted coin will turn up heads
"""
self.n_flips = n_flips
self.n_trials = n_trials
self.weight_heads = weight_heads
self.coins_weighted = coins_weighted
def fair_coin_toss(self):
"""
Function to simulate a single fair coin toss
"""
flip = randint(1,2)
if flip == 1:
return 'heads'
else:
return 'tails'
def weighted_coin_toss(self):
"""
Function to simulate a single weighted coin toss
"""
## Establish percentenge of heads and tails for weighted coin
percent_heads = self.weight_heads
percent_tails = 100-percent_heads
## Use the probabilities to weight the coutcome
pull_heads = randint(1, percent_heads)
pull_tails = randint(1, percent_tails)
if pull_heads < pull_tails:
return 'tails'
else:
return 'heads'
def flip_trial(self, trial_type):
"""
Function to carry out a trial flipping n_flips times
"""
flips_heads = 0
flips_tails = 0
for i in range(self.n_flips):
if trial_type == 'fair':
coin_toss = self.fair_coin_toss()
if trial_type == 'weighted':
coin_toss = self.weighted_coin_toss()
if coin_toss == 'heads':
flips_heads += 1
return flips_heads
def population_trial_distributions(self):
"""
Function to carry n_trials
Returns:
weighted_trials_distributions: a list where each element is the number of heads
that came up in a simulated trial using a weighted coin.
fair_trials_distributinos: a list where each element is the number of heads that
came up in a simulated trial using a fair coin.
"""
weighted_trials_distributions = []
fair_trials_distributions = []
n_weighted_trials = (float(self.coins_weighted))*self.n_trials
for n in range(self.n_trials):
if n < n_weighted_trials:
weighted_trial_heads = self.flip_trial('weighted')
weighted_trials_distributions.append(weighted_trial_heads)
else:
fair_trial_heads = self.flip_trial('fair')
fair_trials_distributions.append(fair_trial_heads)
return weighted_trials_distributions, fair_trials_distributions