Random numbers drive simulations, sampling, shuffling and the initialisation of ML models. Chapter 4 introduced default_rng; this chapter is the full toolkit — the distributions you can draw from and how to use randomness to answer real questions by simulation.
The Generator API
Modern NumPy uses a Generator object from np.random.default_rng. Seed it for reproducibility; prefer it over the legacy np.random.seed/np.random.rand functions:
rng = np.random.default_rng(seed=42) # reproduciblerng.random(3) # 3 floats in [0, 1)rng.integers(1, 7, size=10) # 10 dice rolls (1–6)
Drawing from distributions
Sampling from named distributions is how you model real processes — heights, wait times, noise:
rng.normal(loc=170, scale=7, size=1000) # heights ~ N(170, 7)rng.uniform(0, 1, size=5) # uniform floatsrng.poisson(lam=3, size=10) # counts of rare eventsrng.binomial(n=10, p=0.5, size=5) # coin-flip successes
Shuffling & sampling
deck = np.arange(52)rng.shuffle(deck) # shuffle in placerng.permutation(5) # a shuffled [0..4] (returns a copy)rng.choice(["A", "B", "C"], size=4, p=[0.7, 0.2, 0.1]) # weighted drawrng.choice(100, size=10, replace=False) # sample without replacement
Monte-Carlo simulation
Monte-Carlo methods answer hard questions by simulating many random trials and averaging. Here we estimate π by throwing darts at a square:
n = 1_000_000x = rng.random(n)y = rng.random(n)inside = (x**2 + y**2) <= 1 # fell inside the quarter circle?pi_est = 4 * inside.mean() # ≈ 3.1416# More trials → closer estimate. This is vectorised — no Python loop.
Practice
Simulate 10,000 rolls of two dice and estimate the probability the sum is 7. Draw 1,000 samples from a normal distribution and check the mean and std match what you asked for. Use a Monte-Carlo simulation to estimate π and watch the estimate improve as you increase the trial count.
Key takeaways
- 01Use np.random.default_rng(seed) — the modern Generator API — over the legacy functions.
- 02Draw from named distributions (normal, uniform, poisson, binomial) to model real processes.
- 03shuffle permutes in place; permutation returns a copy; choice samples (weighted, with/without replacement).
- 04Monte-Carlo simulation answers hard questions by averaging many random trials.
- 05Seeding makes randomness reproducible — essential for debuggable experiments.
