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
rng = np.random.default_rng(42)rng.random(3) # floats in [0, 1)rng.integers(1, 7, size=10) # dice rollsrng.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:
n = 1_000_000x, y = rng.random(n), rng.random(n)inside = (x**2 + y**2) <= 1pi_est = 4 * inside.mean() # ≈ 3.1416 — fully vectorised, no loop
Key takeaways
- 01Use np.random.default_rng(seed) — the modern Generator API — for reproducible randomness.
- 02Draw from named distributions: random, integers, normal, choice (with weights).
- 03Monte-Carlo simulation answers hard questions by averaging many random trials.
- 04Seeding makes experiments reproducible and debuggable.
