Probability with Python
This lesson is a toolbox tour. Three tools cover almost everything in the course: the standard library's random and fractions for small simulations and exact answers, itertools for listing sample spaces, and NumPy for fast simulation of many trials at once.
Exact answers with fractions
Floating point turns into and loses exactness. Fraction keeps probabilities exact, which is ideal for checking formulas on small problems.
from fractions import Fraction
from itertools import product
dice = list(product(range(1, 7), repeat=2)) # all 36 outcomes
p_sum7 = Fraction(sum(1 for a, b in dice if a + b == 7), len(dice))
p_double = Fraction(sum(1 for a, b in dice if a == b), len(dice))
print("outcomes:", len(dice))
print("P(sum = 7) =", p_sum7)
print("P(double) =", p_double)
print("P(sum = 7 or double) =", p_sum7 + p_double) # disjoint events addoutcomes: 36
P(sum = 7) = 1/6
P(double) = 1/6
P(sum = 7 or double) = 1/3
When all outcomes are equally likely, : count the outcomes in the event, divide by the total. Listing with itertools.product, permutations and combinations is the computer version of counting.
Seeded random numbers
A pseudo-random number generator (PRNG) produces a deterministic sequence that passes statistical tests for randomness. Python's random uses the Mersenne Twister. Creating a random.Random(seed) object gives a reproducible stream:
import random
rng = random.Random(42)
print([rng.randint(1, 6) for _ in range(10)]) # dice
print(round(rng.random(), 6)) # uniform in [0, 1)
print(rng.choice(["heads", "tails"]))
print(rng.sample(range(1, 50), 6)) # lottery draw without replacement
rng2 = random.Random(42)
print([rng2.randint(1, 6) for _ in range(10)]) # same seed, same sequence[6, 1, 1, 6, 3, 2, 2, 2, 6, 1]
0.676699
heads
[38, 28, 3, 2, 6, 14]
[6, 1, 1, 6, 3, 2, 2, 2, 6, 1]
Vectorized simulation with NumPy
Loops in Python handle thousands of trials comfortably; NumPy handles millions. np.random.default_rng(seed) creates a modern generator (PCG64). Simulating many experiments at once is a matter of generating an array and using comparisons and sums along an axis:
import numpy as np
rng = np.random.default_rng(0)
rolls = rng.integers(1, 7, size=(200_000, 4)) # 200,000 experiments of 4 rolls
at_least_one_six = (rolls == 6).any(axis=1)
print("P(at least one six in 4 rolls) ~", at_least_one_six.mean())
print("exact:", round(1 - (5 / 6) ** 4, 4))
totals = rolls.sum(axis=1)
values, counts = np.unique(totals, return_counts=True)
print("most common total of 4 dice:", int(values[counts.argmax()]))P(at least one six in 4 rolls) ~ 0.51801
exact: 0.5177
most common total of 4 dice: 14
Booleans average to frequencies: mean() of a True/False array is the fraction of True values. That one idiom estimates almost any probability.
How precise is a simulation?
With trials, a simulated probability is typically off by about (one standard error, explained in the CLT lessons). For near 0.5 that is : 10,000 trials give about two correct decimals, 1,000,000 about three. Each extra decimal costs 100 times more work.
In software
Reproducibility matters in practice: seeded generators make simulations, randomized tests and ML training runs repeatable, and many frameworks have a global seed setting. For security (tokens, passwords, keys) never use random; use secrets, which draws from the operating system's cryptographic generator.
Exercises
Exercise 1: Count by listing
Two dice are rolled. What is the probability that the larger value is 4?
Answer
.
Solution
Max at most 4: outcomes; max at most 3: . Max exactly 4: outcomes out of 36.
Exercise 2: Standard error
About how many trials do you need for a simulated probability near 0.5 to have a standard error of 0.001?
Answer
About 250,000.
Solution
gives , so .
Exercise 3: Check with code
Verify Exercise 1 by listing outcomes with Fraction, and by a NumPy simulation of 100,000 rolls of two dice.
Answer
Exact ; the simulation is close.
Solution
from fractions import Fraction
from itertools import product
import numpy as np
exact = Fraction(sum(1 for a, b in product(range(1, 7), repeat=2) if max(a, b) == 4), 36)
rng = np.random.default_rng(3)
r = rng.integers(1, 7, size=(100_000, 2))
print(exact, round(float(exact), 4), (r.max(axis=1) == 4).mean())7/36 0.1944 0.19427
Test yourself
What does (arr == 6).mean() compute for a NumPy array of die rolls?
- The average roll
- The fraction of rolls equal to 6
- The number of sixes
- The index of the first six
Which module should generate a password-reset token?
- random
- numpy.random
- secrets
- itertools
To gain one more correct decimal in a simulated probability you need about…
- twice as many trials
- 10 times as many trials
- 100 times as many trials
- one more trial