Skip to content

Discovering the World of Probabilities with Python

My kids came home today and were talking about a problem they were given in Maths class at school. They had to work out the probability of this problem:

Imagine rolling two six-sided dice and multiplying the numbers that land face-up. We want to find out how often the product of these two numbers is divisible by 6.

According to probability theory, we should expect this to happen about 5/12 of the time.

They then asked that rather than calculating the probability, could they just roll the dice a large number of times?

Their teacher (the formidable Mrs. D.) said – you could but if you rolled then the dice the same number of times again, you’d get a different answer. Mrs. D. was completely correct!

I thought it would be cool to simulate this kind of brute force method using Python.

Here is the script that I knocked together to simulate dice rolls and multiplying the results together:

""" Roll 2 six sided dice a number of times and multiply them together. 
    We then record the number of results are evenly divisible by 6 and express it 
    as a percentage. Should get close to 5/12 """

import random

rolls = 1000

divisible_by_six = 0

print(f"Rolling {rolls} sets of 2d6")

for i in range(rolls):
    result = random.randint(1, 6) * random.randint(1, 6)
    if result % 6 == 0:
        divisible_by_six += 1

calc_percent = divisible_by_six / rolls * 100
expected_percent = 5/12 * 100

print(f"Result: {divisible_by_six} divisible by six out of {rolls} rolls.")
print(f"This is {calc_percent}% - expected is {expected_percent}%")
print(f"Difference is {calc_percent-expected_percent} %")

Breaking Down the Code

  1. We import the random module to help us simulate the dice rolls.
  2. We decide to conduct the experiment with a thousand rolls to get a sizable sample.
  3. As we loop through each roll, we multiply the results of rolling two dice and check if the product is divisible by 6, incrementing our counter if true.
  4. At the end of the loop, we calculate the percentage of times the condition was met and compare it with the theoretical expectation of 5/12.


After running the script, you’ll notice that the experimental percentage closely aligns with the theoretical expectation, showcasing the power and reliability of probability theory.

The more dice rolls you do – the closer we get to the theorectical probability.

Feel free to tweak the script, maybe increase the number of rolls, and observe how the results vary. It’s a great way to learn and have fun at the same time!

You’ll find that ‘rolling the dice’ one million times gives a much more accurate result than rolling it 1000 times. Why would that be?

That’s all for today people! Happy coding, and until next time, keep experimenting and learning!


Leave a Reply