# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import numpy as np
import matplotlib.pyplot as plt


def binomial(n, p):
    # Sample from a uniform distribution
    u = np.random.rand(n)
    
    # a draw is successful if probability is less than p
    return sum(u < p)


# +
# number of trials (of binomial)
n_trial = 10000

# number of draw (in each binomial trial)
n = 100

# probability of success
p = 0.8

# when n_trial is large, binomial tends to normal distribution
m = [binomial(n, p) for _ in range(n_trial)]
plt.hist(m, density=True)
plt.show()
# -

print("""
mean empirical: %.2f
mean analytical: %.2f
variance empirical: %.2f
variance analytical: %.2f
"""%(np.mean(m), n * p, np.var(m), n * p * (1 - p)))

# ##### Using Numpy

# +
# number of trials (of binomial)
n_trial = 10000

# number of draw (in each binomial trial)
n = 100

# probability of success
p = 0.8

# when n_trial is large, binomial tends to normal distribution
m = np.random.binomial(p=p, n=n, size=n_trial)
plt.hist(m, density=True)
plt.show()

StarcoderdataJupyterScriptsDedupFiltered