How to seed a NumPy random generator

Pseudo-random values come from a stateful sequence rather than a source of unpredictable events. An explicit seed gives a NumPy Generator a repeatable starting state for tests, simulations, and examples that must replay the same draws.

The np.random.default_rng() constructor creates an independent generator instead of changing the legacy module-wide random state. Each draw advances that object, while a new generator initialized from the same seed starts the sequence again.

Keep the seed at the boundary of a run and pass the generator to code that needs random values. Generator streams are not guaranteed to stay identical across NumPy versions, and statistical generators are not suitable for passwords, tokens, or other cryptographic material.

Steps to seed a NumPy random generator:

  1. Create the first section of random-generator-seed.py with one run-level seed and two draws from a single Generator.
    random-generator-seed.py
    import numpy as np
     
    SEED = 2026
    rng = np.random.default_rng(SEED)
     
    first_draw = rng.integers(0, 20, size=8)
    next_draw = rng.integers(0, 20, size=8)

    A stored non-negative integer makes the starting state reusable without resetting the active generator.

  2. Append the replay section to random-generator-seed.py.
    random-generator-seed.py
    replay_rng = np.random.default_rng(SEED)
    replayed_first_draw = replay_rng.integers(0, 20, size=8)
     
    print("seed:", SEED)
    print("first draw:", first_draw)
    print("next draw:", next_draw)
    print("replayed first draw:", replayed_first_draw)
    print("replay matches first:", np.array_equal(replayed_first_draw, first_draw))
    print("next draw differs:", not np.array_equal(next_draw, first_draw))

    The replay generator is a separate object. Creating it does not reset or alter the state already held by rng.

  3. Run random-generator-seed.py to confirm that recreating the generator replays the first draw while the original generator advances.
    $ python3 random-generator-seed.py
    seed: 2026
    first draw: [17  3  0 12  7  9  1  7]
    next draw: [12  7 16 15 14 18 14  3]
    replayed first draw: [17  3  0 12  7  9  1  7]
    replay matches first: True
    next draw differs: True

    Both True lines are required. A False replay result means the seed, draw method, bounds, shape, or draw order differs between the original and replay generators.