Let us consider an experiment of tossing a biased coin, in which p is the probability of 'heads' and n is the number of tosses. An experiment is defined as a series of trials. In this case, an experiment will consist of n trials/tosses. We will repeat the experiment 1000 times to simulate the binomial distribution.
We must check if the experiment follows the assumptions of binomial distribution:
Consider n tosses of a coin. Since the tosses are independent, we can calculate the probability of an outcome by multiplying the individual probabilities in each toss. Probability of 'heads' is p and that of 'tails' is 1-p. Outcome of one experiment with n tosses, has k heads and n-k tails and has probability pk(1-p)3-k. There are ${n} \choose {k}$ number of distinct n-toss sequences that contain k heads. This forms the binomial coefficient.
Binomial probability mass function (pmf) = ${n} \choose {k}$ pk(1-p)n-k
We can now go ahead and simulate our experiment.
%matplotlib inline
import random
from scipy.stats import binom
import matplotlib.pyplot as plt
def toss(p,n):
heads = 0
for i in range(n):
if random.random() < p:
heads += 1
return heads #This gives the number of heads in a single experiment of n trials
size = range(1,1000)
n,p = 30,0.6
k = [] #Holds the number of heads from each experiment
pmf= [] #Holds the binomial pmf of each experiment
random.seed(12345)
Use toss function to create list of k values, sort them and for each k, calculate pmf using binom.pmf function. Plot k and pmf to get the distribution plot.
for i in size:
k.append(toss(p,n))
k.sort()
for i in k:
pk = binom.pmf(i,n,p)
pmf.append(pk)
plt.plot(k,pmf)
[<matplotlib.lines.Line2D at 0x11cb827b8>]
ref_tmp_var = False
try:
head = k[:10]
prob = pmf[:10]
ks = [9, 9, 10, 10, 11, 11, 11, 11, 12, 12]
pmfs = [round(x,4) for x in [0.00063412401653505015, 0.00063412401653505015, 0.0019974906520854141, 0.0019974906520854141, 0.005447701778414739, 0.005447701778414739, 0.005447701778414739, 0.005447701778414739, 0.012938291723735, 0.012938291723735]]
if ks == head and pmfs == [round(a,4) for a in prob]:
ref_assert_var = True
ref_tmp_var = True
else:
ref_assert_var = False
print('Please follow the instructions given and use the same variables provided in the instructions. ')
except Exception:
print('Please follow the instructions given and use the same variables provided in the instructions. ')
assert ref_tmp_var
continue