Skip to main content
Albero Academy

Random Sampling & Simulation

The modern Generator API — draw from distributions, shuffle and sample, and run Monte-Carlo simulations reproducibly.

Chapter 10NumPy15 min readBeginner friendly
  • #NumPy
  • #Random
  • #Simulation

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:

create a generator
rng = np.random.default_rng(seed=42) # reproducible
rng.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:

named distributions
rng.normal(loc=170, scale=7, size=1000) # heights ~ N(170, 7)
rng.uniform(0, 1, size=5) # uniform floats
rng.poisson(lam=3, size=10) # counts of rare events
rng.binomial(n=10, p=0.5, size=5) # coin-flip successes

Shuffling & sampling

permute & choose
deck = np.arange(52)
rng.shuffle(deck) # shuffle in place
rng.permutation(5) # a shuffled [0..4] (returns a copy)
rng.choice(["A", "B", "C"], size=4, p=[0.7, 0.2, 0.1]) # weighted draw
rng.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:

estimating π by simulation
n = 1_000_000
x = 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

  1. 01Use np.random.default_rng(seed) — the modern Generator API — over the legacy functions.
  2. 02Draw from named distributions (normal, uniform, poisson, binomial) to model real processes.
  3. 03shuffle permutes in place; permutation returns a copy; choice samples (weighted, with/without replacement).
  4. 04Monte-Carlo simulation answers hard questions by averaging many random trials.
  5. 05Seeding makes randomness reproducible — essential for debuggable experiments.