Simulating Chance
Coins and dice in code.
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.

- 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.
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))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.
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))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