Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Random Numbers

NumPy Generators and Reproducible Streams

Use numpy.random.default_rng for fast, reproducible simulation, spawn independent streams for parallel work, and avoid common seeding mistakes.

You now know what a PRNG is. In practice you will almost always use one from a library. In Python, the best everyday tool for simulation is NumPy's Generator, created with numpy.random.default_rng. This lesson shows how to use it well, how to make experiments reproducible, and how to create several independent streams without accidental overlap.

Creating and using a Generator

Python
rng = np.random.default_rng(seed)

rng is an object that holds the state. Its methods draw from many distributions, and each accepts a size argument for whole arrays at once.

Method Draws
rng.random(n) uniform on [0, 1)
rng.uniform(a, b, n) uniform on [a, b)
rng.integers(a, b, n) integers a to bโˆ’1 (the upper end excluded)
rng.normal(mu, sigma, n) normal (bell curve)
rng.exponential(scale, n) exponential, mean scale
rng.choice(arr, n, replace=...) picks from an array
rng.permutation(n) a shuffled 0..nโˆ’1
rng.binomial(trials, p, n) number of successes
Python A tour of Generator methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that integers(1, 7) gives 1 to 6: the upper bound is excluded. This catches many beginners.

Reproducibility

A seeded generator produces the same stream every time, on every machine, for the same NumPy version and the same sequence of calls. Two points to remember:

  1. The order of calls matters. Drawing 5 uniform numbers and then 5 normal numbers produces different values than the reverse order.
  2. The stream can change between NumPy versions for some methods (the project guarantees stability for the bit generator but not for every distribution). If you need results to be reproducible for years, record the NumPy version too.
Python Reproducible and order-dependent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pass the generator, not a global

Old tutorials call np.random.seed(0) and np.random.rand(). That uses a hidden global generator, which makes code hard to reason about. Prefer an explicit rng object that you pass into your functions:

Python
def simulate(n, rng):
    return rng.normal(size=n).mean()

This keeps experiments isolated, testable, and ready for parallel use.

Independent streams with SeedSequence

Suppose you run 4 parallel workers, or 4 repetitions that must be independent. A tempting shortcut is seeds 1, 2, 3, 4. Seeds that differ by small numbers usually work in modern generators, but the guaranteed way is NumPy's SeedSequence, which mixes a parent seed into well-separated child seeds.

flowchart TD
  P["SeedSequence(parent seed)"] --> C1["child 1"]
  P --> C2["child 2"]
  P --> C3["child 3"]
  C1 --> G1["Generator 1"]
  C2 --> G2["Generator 2"]
  C3 --> G3["Generator 3"]

One parent seed produces independent child streams.

Python Spawn independent generators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Averaging four independent estimates gives an estimate with half the standard error of a single one (4 times the samples). That is just the 1/โˆšN rule from earlier lessons.

You can also call rng.spawn(k) on an existing generator in recent NumPy versions, which returns k independent child generators.

Speed tip: draw in bulk

Calling the generator once per sample is slow because each call has overhead. Draw large arrays at once whenever memory allows.

Python Loop versus bulk draw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When memory is limited (say, 10โน samples), draw in chunks of a million or so and combine the partial sums.

Quick checklist

  • Create one rng with default_rng(seed); pass it around.
  • Use SeedSequence.spawn (or rng.spawn) for parallel or repeated independent runs.
  • Draw arrays, not single values.
  • Store the seed and the library version with your results.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does rng.integers(1, 7, 10) draw?

    The upper bound is exclusive, so integers(1, 7) gives values 1 through 6.
  2. 2. Why is passing an explicit rng object better than using np.random.seed()?

    An explicit generator keeps each experiment's random stream separate and under your control.
  3. 3. What is SeedSequence.spawn used for?

    spawn derives well-separated child seeds so parallel or repeated runs do not overlap.
  4. 4. Which order of operations gives the same numbers: draw uniform then normal, or normal then uniform, from the same seed?

    Each call advances the state, so changing the order changes which numbers each call receives.

Summary

  • Use rng = np.random.default_rng(seed) and call its methods for uniform, normal, integers and more.
  • Seeds make runs reproducible, but call order matters, and library versions can matter too.
  • Pass the generator explicitly instead of relying on global state.
  • SeedSequence.spawn gives independent streams for repeated or parallel runs.
  • Draw samples in bulk for speed.

Next: Inverse Transform Sampling