In [1]:
# Goal: generate random variables from a fixed distribution
# and take average
In [26]:
randint(0,1) # {0,1} uniform random variable
Out[26]:
1
In [11]:
random() # [0,1] uniform  
Out[11]:
0.9784427165891055
In [12]:
2*randint(0,1)-1 # {-1,1} uniform
Out[12]:
-1
In [19]:
2*random() #[0,2] uniform
Out[19]:
0.5334555997916841
In [27]:
# sum of list 
sum([0,1,2,3])
Out[27]:
6
In [29]:
def ave_rand_01discrete(n):
    """Generate n independent instances of randint(0,1).
    Takes average of these."""
    list_rand = [randint(0,1) for i in range(n)]
    return sum(list_rand)/n
In [47]:
ave_rand_01discrete(2)
Out[47]:
1/2
In [ ]:
# plot runs of the above as histogram 
In [49]:
import matplotlib.pyplot as plt
# plt is now shorthand for matplotlib.pyplot
In [50]:
plt.hist([0,1,2,2,3])
Out[50]:
(array([1., 0., 0., 1., 0., 0., 2., 0., 0., 1.]),
 array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3. ]),
 <a list of 10 Patch objects>)
In [59]:
plt.hist([randint(0,1) for i in range(1000)])
# gives a good picture of one random variable
Out[59]:
(array([474.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0., 526.]),
 array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
 <a list of 10 Patch objects>)
In [62]:
# now take a bunch of instances of ave_rand_01discrete
plt.hist([ave_rand_01discrete(2) for i in range(10000)])
Out[62]:
(array([2493.,    0.,    0.,    0.,    0., 4995.,    0.,    0.,    0.,
        2512.]),
 array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
 <a list of 10 Patch objects>)
In [65]:
# now take a bunch of instances of ave_rand_01discrete
plt.hist([ave_rand_01discrete(10) for i in range(10000)])
Out[65]:
(array([  10.,   93., 1542.,    0., 2041., 4583., 1196.,    0.,  423.,
         112.]),
 array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
 <a list of 10 Patch objects>)
In [66]:
plt.hist([ave_rand_01discrete(100) for i in range(10000)])
# NOTE: scale on horizontal axis
# Histograms are getting concentrated around
# average of a single {0,1} discrete r.v.
Out[66]:
(array([  11.,   88.,  355., 1358., 1990., 3117., 2167.,  619.,  259.,
          36.]),
 array([0.31 , 0.346, 0.382, 0.418, 0.454, 0.49 , 0.526, 0.562, 0.598,
        0.634, 0.67 ]),
 <a list of 10 Patch objects>)
In [68]:
plt.hist([ave_rand_01discrete(1000) for i in range(10000)])
Out[68]:
(array([  11.,  111.,  628., 1769., 3096., 2698., 1247.,  383.,   52.,
           5.]),
 array([0.439 , 0.4517, 0.4644, 0.4771, 0.4898, 0.5025, 0.5152, 0.5279,
        0.5406, 0.5533, 0.566 ]),
 <a list of 10 Patch objects>)
In [ ]:
# Law of Large Numbers