AI Hints
Statistics & Math for ML · Lesson 26 of 138

Simulating Chance

Coins and dice in code.

⏱ 2 min read▶ Video at 29:20🎓 Free
Watch this lesson in the Statistics & Math for ML courseWatch on YouTube ↗Full Statistics & Math for ML course

Here's a superpower. When a probability question is hard to work out on paper, you can simply simulate it. Let the computer play the game a million times, and count how often something happens.

Simulating Chance
From the video: Simulating Chance
  • Hard probability question?
  • Simulate it
  • Play a million times and count

A million dice

We roll a million dice with integers, from one up to, but not including, seven. Then we count how often we rolled a six, by averaging a true or false array. Run it. Very close to one sixth, which is about zero point one six seven.

dice.pypython
import numpy as np

rng = np.random.default_rng(0)
rolls = rng.integers(1, 7, size=1_000_000)

print("P(six) ~", (rolls == 6).mean().round(4))
print("exact:  ", round(1 / 6, 4))
Output
P(six) ~ 0.1669
exact:   0.1667

A harder question

What's the chance that two dice add up to seven? We roll two columns of dice, and add them. Run it. About one in six, again. On paper, you'd count six ways out of thirty six. The simulation found the same answer without any thinking.

two_dice.pypython
import numpy as np

rng = np.random.default_rng(1)
a = rng.integers(1, 7, size=1_000_000)
b = rng.integers(1, 7, size=1_000_000)

print("P(sum is 7) ~", ((a + b) == 7).mean().round(4))
Output
P(sum is 7) ~ 0.1664

Summary

When the maths is hard, simulate. Generate lots of random trials, and count how often your event happens. Next, why more trials give better answers.

Key takeaways
  • rng.integers
  • Average a True/False array
  • Simulate to check
Next up: The Law of Large Numbers — more trials, better answers