Lecture 32 – Randomness and Simulations

Data 94, Spring 2021

In [1]:
from datascience import *
import numpy as np
Table.interactive_plots()

from ipywidgets import interact, widgets
from IPython.display import display

Randomness

np.random.randint and seeds

Each time you run this cell, you will get a random integer between 1 and 10 inclusive.

In [2]:
np.random.randint(1, 11)
Out[2]:
9

Each time you run this cell, you will get the number 9. Changing the seed (15) to something else may change the number you see. The seed is local to the cell only (no other cells in your notebook are affected by the np.random.seed(15) line).

In [3]:
np.random.seed(15)
np.random.randint(1, 11)
Out[3]:
9

The size argument allows us to get back an array instead of a single number.

In [4]:
np.random.seed(12)
np.random.randint(25, size = 5)
Out[4]:
array([11,  6, 17,  2,  3])

Notice that the first five numbers in the following array are the same as in the array above.

In [5]:
np.random.seed(12)
np.random.randint(25, size = 15)
Out[5]:
array([11,  6, 17,  2,  3,  3, 12, 16, 22, 17, 20,  5, 13,  2, 11])

Note that when I save an array to a variable, its result doesn't change unless I call np.random.randint again.

In [6]:
nums = np.random.randint(10, size = 5)
nums
Out[6]:
array([6, 0, 5, 8, 2])
In [7]:
# Will be the same as whatever is shown above, since we're not calling np.random.randint again
nums
Out[7]:
array([6, 0, 5, 8, 2])
In [8]:
# Still the same, since we're not calling np.random.randint again
nums
Out[8]:
array([6, 0, 5, 8, 2])

np.random.choice

In [9]:
coin = np.array(['heads', 'tails'])

This is equivalent to flipping a fair coin once.

In [10]:
np.random.choice(coin)
Out[10]:
'tails'

This is equivalent to flipping a fair coin 10 times.

In [11]:
np.random.choice(coin, 10)
Out[11]:
array(['tails', 'heads', 'heads', 'tails', 'tails', 'heads', 'tails',
       'tails', 'heads', 'heads'], dtype='<U5')

Simulations

Example: dice rolls

In [12]:
np.random.randint(1, 7, size = 100)
Out[12]:
array([3, 1, 5, 4, 6, 2, 6, 1, 1, 4, 4, 2, 4, 1, 2, 2, 1, 5, 1, 5, 2, 4,
       5, 6, 4, 6, 4, 5, 6, 4, 6, 4, 5, 1, 3, 6, 4, 3, 5, 3, 3, 4, 5, 4,
       2, 5, 4, 6, 2, 5, 6, 2, 6, 4, 6, 4, 1, 4, 3, 2, 6, 5, 3, 4, 4, 3,
       5, 6, 3, 1, 1, 6, 5, 1, 4, 6, 2, 1, 2, 5, 2, 5, 6, 3, 2, 4, 4, 5,
       3, 5, 1, 1, 5, 5, 5, 4, 4, 2, 5, 3])
In [ ]:
# Don't worry about the code, just play with the slider that appears after running.
w = widgets.FloatLogSlider(
    value=1000,
    base=10,
    min=0, # max exponent of base
    max=6, # min exponent of base
    step=0.2, # exponent step
    description='Log Slider'
)

def rolls_hist(scale):
    scale = int(scale)
    rolls = np.random.randint(1, 7, size = scale)
    fig = Table().with_columns('Number of Rolls', rolls).hist(density = False, 
                                                              bins = np.arange(0.5, 7.5),
                                                              title = f'Empirical Distribution of {scale} Dice Rolls',
                                                              show = False)
    display(fig)
    
interact(rolls_hist, scale=w);

Note: The term "empirical" means "from an experiment or simulation" (as opposed to theoretical).

Also note that the histogram is randomly generated each time you move the slider, so if you select 1000, move to some other number, and come back to 1000, the histogram will look different than it did before. (Setting the seed would prevent this from happening.)

Example: sum of dice rolls

In [13]:
np.random.randint(1, 7, 100)
Out[13]:
array([5, 4, 1, 3, 1, 2, 1, 5, 2, 5, 2, 5, 5, 2, 3, 4, 5, 4, 4, 3, 1, 4,
       5, 6, 1, 2, 5, 6, 5, 3, 3, 3, 1, 2, 3, 6, 3, 3, 1, 2, 5, 3, 2, 2,
       2, 4, 1, 2, 5, 6, 1, 5, 3, 1, 1, 1, 1, 5, 4, 2, 4, 6, 2, 4, 3, 4,
       5, 2, 2, 6, 4, 3, 3, 4, 1, 2, 4, 6, 2, 2, 5, 6, 6, 1, 6, 1, 4, 2,
       5, 3, 3, 3, 5, 1, 1, 4, 6, 3, 3, 5])

This array is the result of simulating the act of rolling two die and adding their results, 100 times.

In [14]:
np.random.randint(1, 7, 100) + np.random.randint(1, 7, 100)
Out[14]:
array([11,  7,  4,  5,  5, 11,  7,  9,  5,  7, 12,  5,  7,  7,  7,  8,  5,
        9,  7, 10,  5,  6,  4, 11,  8,  7,  7,  6,  2,  8,  8,  7,  2,  5,
        6,  9,  5,  7,  8,  7,  8,  8,  8,  7,  6,  7,  8,  8,  6,  6, 11,
        4,  5,  7,  6,  3,  5,  2,  5,  7,  4,  6,  8,  8,  6, 10, 11,  9,
        5,  5,  8, 12,  4,  7,  7,  4,  6,  9,  8,  5,  3,  5,  5,  9, 11,
        8, 11,  7,  4,  4,  6,  9,  9,  4,  8,  2, 12,  4,  6,  6])

Let's once again see what happens when we simulate this process a varying number of times.

In [ ]:
# Don't worry about the code, just play with the slider that appears after running.
def sum_rolls_hist(scale):
    scale = int(scale)
    rolls = np.random.randint(1, 7, size = scale) + np.random.randint(1, 7, size = scale)
    fig = Table().with_columns('Number of Rolls', rolls).hist(density = False, 
                                                              bins = np.arange(1.5, 13.5),
                                                              title = f'Empirical Distribution of the Sum of Two Dice Rolls, Repeated {scale} Times',
                                                              show = False)
    display(fig)
    
interact(sum_rolls_hist, scale=w);

Quick Check 1

In [15]:
rolls = np.random.randint(1, 7, size = 5)
A = 2 * rolls
B = rolls + np.random.randint(1, 7, size = 5)

Repetition

In [16]:
coin
Out[16]:
array(['heads', 'tails'], dtype='<U5')
In [17]:
flips = np.random.choice(coin, size = 10)
flips
Out[17]:
array(['heads', 'heads', 'heads', 'tails', 'heads', 'heads', 'tails',
       'heads', 'heads', 'heads'], dtype='<U5')
In [18]:
# Array of 10 elements – True if flip was 'heads', False otherwise
flips == 'heads'
Out[18]:
array([ True,  True,  True, False,  True,  True, False,  True,  True,
        True])
In [19]:
# Number of heads
np.count_nonzero(flips == 'heads')
Out[19]:
8

Simulating Coin Flips

Idea:

  1. Flip a coin 100 times. Write down the number of heads.
  2. Repeat step 1 many times – say, 10,000 times.
  3. Draw a histogram of the number of heads in each iteration.
In [20]:
num_heads_arr = np.array([])

for i in np.arange(10000):
    flips = np.random.choice(coin, size = 100)
    heads = np.count_nonzero(flips == 'heads')
    num_heads_arr = np.append(num_heads_arr, heads)
In [21]:
num_heads_arr
Out[21]:
array([45., 44., 42., ..., 54., 51., 48.])
In [22]:
len(num_heads_arr)
Out[22]:
10000
In [23]:
Table().with_columns('Number of Heads', num_heads_arr) \
       .hist(density = False, bins = np.arange(25.5, 76.5), title = 'Empirical Distribution of 100 Coin Flips')