Probability example
In this exercise, we will review the difference between sampling with and without replacement. We will calculate the probability of an event using simulation, but vary our sampling method to see how it impacts probability.
Consider a bowl filled with colored candies - three blue, two green, and five yellow. Draw three candies, one at a time, with replacement and without replacement. You want to calculate the probability that all three candies are yellow.
This exercise is part of the course
Statistical Simulation in Python
Exercise instructions
- Set up your
bowl
as a list having three blue'b'
, two green'g'
and five yellow'y'
candies. - Draw a sample of three candies with replacement (
sample_rep
) and without replacement (sample_no_rep
). - For the sample with replacement, if there are no
'b'
or'g'
candies insample_rep
, incrementsuccess_rep
. Similarly, incrementsuccess_no_rep
when there are no'b'
or'g'
candies insample_no_rep
. - Calculate the respective probabilities as successes divided by number of iterations.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Set up the bowl
success_rep, success_no_rep, sims = 0, 0, 10000
bowl = list(____*3 + ____*2 + ____*5)
for i in range(sims):
# Sample with and without replacement & increment success counters
sample_rep = np.random.____(bowl, size=3, replace=____)
sample_no_rep = np.random.____(bowl, size=3, replace=____)
if ('b' not in sample_rep) & ('g' not in sample_rep) :
____
if ('b' not in sample_no_rep) & ('g' not in sample_no_rep) :
____
# Calculate probabilities
prob_with_replacement = ____/sims
prob_without_replacement = ____/sims
print("Probability with replacement = {}, without replacement = {}".format(prob_with_replacement, prob_without_replacement))