Simulating probability events in Python

Elliott Saslow
Jul 10, 2018 · 3 min read

Have you ever… had an annoying long probability problem, that seemed to have no answer? Well, today is your lucky day, we are going to explore how to use python to solve basic probability problems and then apply these skills to a couple of challenge problems!

Two unbiased dice are thrown once and the total score is observed. Use a simulation to find the estimated probability that the total score is even or greater than 7?

  • We could use a mathematical equation to solve this or we can run the experiment many times, and then count the number to times where the score is even or greater than 7
  1. Run the experiment 1000 times (roll 2 dice 1000 times, and sum the result)
  2. Keep track of the number of times that the sum was either greater than 7 or even
  3. Divide the number from step 2 by the number of iterations (1000)

Lets take a look at the distribution of rolling 2 dice and summing it so that we can have a general idea of what our answer will be:

Histogram of sum of 2 dice after rolling

From looking at the above graph, we would expect that the probability of an even number or greater than 7 would be larger than 50%. So now, lets write some sudo code to do this, and calculate out the actual percentage:

Awesome! Now lets actually code this up and see what the probability is!

How to run the simulation in python

Awesome, so the answer is 66% which we could have calculated in other ways! Now lets check out how we would use a similar system to solve a more difficult problem. This time, I will not be writing out the pseudo code, but the actual code is included below.

A box contains 10 white balls, 20 reds and 30 greens. Draw 5 balls with replacement… what is the probability that:

a. 3 white or 2 red

b. All 5 are the same color

We will use the same system here. We will pick our balls during each round and count the number of times that a. 3 white or 2 red || b. All 5 are the same color. Below is code to do that.

How to calculate the probability for a different question

For help with Python, Unix or anything Computer Science, book a time with me on EXL skills

Future Vision

A publication centered around high quality storytelling

Elliott Saslow

Written by

Future Vision

A publication centered around high quality storytelling

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade