# CS 237 Spring 2019
# Author: Alina Ene (aene@bu.edu)
# Used in L1
In this notebook, we perform two experiments to empirically answer the following questions:
Q1: We roll a fair die repeatedly until we roll a 6. How many rolls do we expect?
Q2: We roll a fair die repeatedly until we roll a 6. How many rolls do we expect given than all the rolls gave even numbers?
import numpy as np
from numpy.random import randint
import matplotlib.pyplot as plt
plt.style.use('seaborn')
# simulation for Q1
# a single experiment
def single_trial_Q1():
num_rolls = 0
while True:
num_rolls = num_rolls + 1
die_roll = randint(1, 7) #fair die roll
if die_roll == 6:
break
return num_rolls
# perform N trials
N = 1000
rolls = []
trial = [i + 1 for i in range(N)]
for i in range(N):
num_rolls = single_trial_Q1()
rolls.append(num_rolls)
avg_rolls = sum(rolls)
avg_rolls = avg_rolls / N
# plot results
plt.bar(trial,rolls)
plt.xlabel("Trial")
plt.ylabel("Number of rolls")
plt.title("average = " + str(avg_rolls),fontsize=20)
plt.show()
# simulation for Q2
# a single experiment
def single_trial_Q2():
num_rolls = 0
while True:
num_rolls = num_rolls + 1
die_roll = randint(1, 7) #fair die roll
if die_roll == 1 or die_roll == 3 or die_roll == 5:
# restart the experiment
num_rolls = 0
continue
if die_roll == 6:
break
return num_rolls
# perform N trials
N = 10000
rolls = []
trial = [i + 1 for i in range(N)]
for i in range(N):
num_rolls = single_trial_Q2()
rolls.append(num_rolls)
avg_rolls = sum(rolls)
avg_rolls = avg_rolls / N
plt.bar(trial,rolls)
plt.xlabel("Trial")
plt.ylabel("Number of rolls")
plt.title("average = " + str(avg_rolls),fontsize=20)
plt.show()