In [1]:
from __future__ import division
In [2]:
import random
def random_kid():
return random.choice(['boy','girl'])
In [3]:
both_girls = 0
older_girl = 0
either_girl = 0
In [4]:
random.seed(0)
for _ in xrange(10000):
younger = random_kid()
older = random_kid()
if older == 'girl':
older_girl += 1
if older == 'girl' and younger == 'girl':
both_girls += 1
if older == 'girl' or younger == 'girl':
either_girl += 1
In [5]:
print 'P(both | older):', both_girls / older_girl
print 'P(both | either):', both_girls / either_girl
In [6]:
def uniform_pdf(x):
return 1 if x >= 0 and x < 1 else 0
def uniform_cdf(x):
if x < 0:
return 0
elif x < 1:
return x
else:
return 1
In [8]:
import math
def normal_pdf(x, mu = 0, sigma = 1):
sqrt_two_pi = math.sqrt(2 * math.pi)
return (math.exp(-(x-mu)**2/ 2 / sigma**2) / (sqrt_two_pi * sigma))
def normal_cdf(x, mu = 0, sigma = 1):
return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2
# binary search to make inverse normal
def inverse_normal_cdf(p, mu = 0, sigma = 1, tolerance = 0.0001):
# make sure it's standard normal
if mu != 0 or sigma != 1:
return mu + sigma * inverse_normal_cdf(p, tolerance = tolerance)
low_z, low_p = -10.0, 0
hi_z, hi_p = 10.0, 1
while hi_z - low_z > tolerance:
mid_z = (low_z + hi_z) / 2
mid_p = normal_cdf(mid_z)
if mid_p < p:
low_z, low_p = mid_z, mid_p
elif mid_p > p:
hi_z, hi_p = mid_z, mid_p
else:
break
return mid_z
In [12]:
inverse_normal_cdf(0.05)
Out[12]:
In [13]:
def bernoulli_trial(p):
return 1 if random.random() < p else 0
def binomial(n, p):
return sum(bernoulli_trial(p) for _ in xrange(n))
In [16]:
# Investigate it
from collections import Counter
def make_hist(p, n, num_points):
data = [binomial(n, p) for _ in xrange(num_points)]
histogram = Counter(data)
return histogram
In [17]:
make_hist(0.6, 5000, 100)
Out[17]:
In [ ]: