Seeded random generators make NumPy examples, tests, and simulations repeatable without using the older global random state. A fixed seed gives a Generator a defined starting point, so the same first draws can be replayed when the generator is recreated.

np.random.default_rng(seed=…) creates an independent generator object. The object owns its state, so each random draw advances the sequence; creating a new generator with the same seed returns to the start of that sequence.

Keep the seed at the boundary of the run, then pass the generator object into functions that need random values. Leave the seed out for exploratory randomness, and use Python's secrets module instead of NumPy for security tokens or cryptographic random values.

Steps to seed a NumPy random generator:

  1. Create a script that stores the seed once and passes the generator into the random-draw function.
    random-generator-seed.py
    import numpy as np
     
    SEED = 2026
     
     
    def draw_batch(rng):
        return rng.integers(0, 20, size=8)
     
     
    rng = np.random.default_rng(seed=SEED)
    first_draw = draw_batch(rng)
    next_draw = draw_batch(rng)
     
    replay_rng = np.random.default_rng(seed=SEED)
    replayed_first_draw = draw_batch(replay_rng)
     
    print("seed:", SEED)
    print("first draw:", first_draw)
    print("next draw:", next_draw)
    print("replayed first draw:", replayed_first_draw)
    print("first draw matches replay:", np.array_equal(first_draw, replayed_first_draw))
    print("next draw matches first:", np.array_equal(next_draw, first_draw))

    Create the generator once for a run and pass that object around. Recreate a generator with the same seed only when the sequence should restart.

  2. Run the script from the Python environment that has NumPy installed.
    $ python 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]
    first draw matches replay: True
    next draw matches first: False

    The replayed first draw matches because it starts from the same seed. The next draw differs because the first generator state already advanced.

  3. Remove the verification script when it was only used to check the seed pattern.
    $ rm random-generator-seed.py