TExcelTAD
Home › Probability Theory › Probability with Python

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 1/31/3 into 0.333…0.333\ldots and loses exactness. Fraction keeps probabilities exact, which is ideal for checking formulas on small problems.

python · try it yourself
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 add
outcomes: 36
P(sum = 7) = 1/6
P(double) = 1/6
P(sum = 7 or double) = 1/3

When all outcomes are equally likely, Pr⁡[E]=∣E∣/∣Ω∣\Pr[E] = \lvert E \rvert / \lvert \Omega \rvert: 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:

python · try it yourself
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:

python · try it yourself
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 nn trials, a simulated probability is typically off by about p(1−p)/n\sqrt{p(1-p)/n} (one standard error, explained in the CLT lessons). For pp near 0.5 that is 0.5/n0.5/\sqrt{n}: 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

7/367/36.

Solution

Max at most 4: 42=164^2 = 16 outcomes; max at most 3: 32=93^2 = 9. Max exactly 4: 16−9=716 - 9 = 7 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

0.5/n=0.0010.5/\sqrt{n} = 0.001 gives n=500\sqrt{n} = 500, so n=250,000n = 250{,}000.

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 7/36≈0.19447/36 \approx 0.1944; the simulation is close.

Solution
python · try it yourself
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?

  1. The average roll
  2. The fraction of rolls equal to 6
  3. The number of sixes
  4. The index of the first six

Which module should generate a password-reset token?

  1. random
  2. numpy.random
  3. secrets
  4. itertools

To gain one more correct decimal in a simulated probability you need about…

  1. twice as many trials
  2. 10 times as many trials
  3. 100 times as many trials
  4. one more trial