Skip to main content
Albero Academy

Random & Simulation

Draw from distributions and answer questions with Monte-Carlo simulation.

Numerical Computing10 min

Random numbers drive simulations, sampling, shuffling and ML initialisation. Modern NumPy uses a Generator object from np.random.default_rng — seed it for reproducibility.

Drawing values

the Generator API
rng = np.random.default_rng(42)
rng.random(3) # floats in [0, 1)
rng.integers(1, 7, size=10) # dice rolls
rng.normal(170, 7, size=1000) # heights ~ N(170, 7)
rng.choice(["A", "B", "C"], size=4, p=[0.7, 0.2, 0.1]) # weighted

Monte-Carlo simulation

Answer hard questions by simulating many random trials and averaging — here, estimating π by throwing darts at a square:

estimating π
n = 1_000_000
x, y = rng.random(n), rng.random(n)
inside = (x**2 + y**2) <= 1
pi_est = 4 * inside.mean() # ≈ 3.1416 — fully vectorised, no loop

Key takeaways

  1. 01Use np.random.default_rng(seed) — the modern Generator API — for reproducible randomness.
  2. 02Draw from named distributions: random, integers, normal, choice (with weights).
  3. 03Monte-Carlo simulation answers hard questions by averaging many random trials.
  4. 04Seeding makes experiments reproducible and debuggable.

Finished this chapter?

Mark it complete to track your progress through NumPy.