Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 49 ยท Random Numbers and Statistics

Random Numbers with Generators

Generate reproducible random numbers in NumPy 2 with default_rng: random, integers, normal, choice, shuffle, permutation, seeds, and independent streams.

Randomness is everywhere in data work: shuffling a dataset, splitting train and test sets, adding noise, running simulations. NumPy's modern way to get random numbers is the Generator, created with np.random.default_rng(). A generator is an object that owns its own random state and has methods for every common draw.

The most important habit this lesson teaches is reproducibility. A computer's "random" numbers come from a deterministic algorithm, so if you start it from the same seed, you get exactly the same numbers every time. That lets you debug, share results and write tests that do not flake.

Creating a generator

np.random.default_rng(seed) returns a Generator. Pass an integer seed to make the sequence repeatable. Pass nothing, and NumPy seeds from fresh operating-system entropy, so every run differs.

Python Seeds make randomness repeatable

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.

flowchart LR
    S["seed 42"] --> G["Generator<br/>(internal state)"]
    G -->|"rng.random()"| N1["0.77, 0.44, 0.86 ..."]
    G -->|"next call"| N2["continues the same stream"]

A seed fixes the whole stream; every call moves the generator's state forward.

A good pattern is to create one generator near the top of your program (or accept one as a function argument) and pass it around, rather than creating a new one in each function.

The main draws

The generator offers one method per kind of draw. Most accept a size argument that can be an integer or a shape tuple.

Method What it returns
rng.random(size) floats in [0, 1)
rng.integers(low, high, size) integers in [low, high) (high excluded)
rng.uniform(low, high, size) floats uniformly between low and high
rng.normal(loc, scale, size) bell-curve floats with mean loc, standard deviation scale
rng.standard_normal(size) normal with mean 0 and standard deviation 1
Python The common draws

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.

Notice integers(1, 7) for a die: the upper bound is excluded, just like in Python's range. Use endpoint=True if you prefer the inclusive version.

Choosing, shuffling and permuting

rng.choice(a, size, replace, p) samples from a list or array. By default it draws with replacement, so the same item can appear twice; set replace=False to deal cards without repeats. The optional p gives each item a probability.

rng.shuffle(x) reorders an array in place and returns None. rng.permutation(x) returns a shuffled copy, or a shuffled 0..n-1 when you give an integer.

Python choice, shuffle and permutation

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.

A reproducible train/test split

Shuffling indexes, instead of the data itself, keeps related arrays aligned:

Python Splitting data reproducibly

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.

Reproducibility: the rules

  • Seeded runs give the same numbers only if you make the same calls in the same order. Insert an extra rng.random() early and everything after it shifts.
  • Reproducibility across NumPy versions is not guaranteed for the random algorithms, but default_rng results are stable in practice for the same version. Store your seed and the NumPy version when publishing results.
  • Never seed from the clock inside a loop. Creating generators with the same time value gives identical streams.
Python Order of calls matters

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.

Legacy: np.random.seed and friends

Older code uses a hidden global generator: np.random.seed(0), np.random.rand(), np.random.randn(), np.random.randint(). These still work, but the global state is shared by everything in the program, which makes tests order-dependent and libraries interfere with each other. Prefer default_rng.

Python Legacy global state versus a Generator

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.

The old RandomState class stays frozen so that old results can be reproduced. The legacy names have equivalents: rand is random, randn is standard_normal, randint is integers (upper bound still excluded).

Independent streams with spawn

What if you run many independent simulations, perhaps in several workers? Seeding them with 1, 2, 3 is not ideal because nearby seeds are not guaranteed to be statistically independent. NumPy provides SeedSequence and spawn to derive well-separated child streams from one parent seed.

Python Spawning 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.

flowchart TD
    P["SeedSequence(12345)"] --> C1["child 0"]
    P --> C2["child 1"]
    P --> C3["child 2"]
    C1 --> G1["Generator A"]
    C2 --> G2["Generator B"]
    C3 --> G3["Generator C"]

One parent seed spawns child seeds that give statistically independent generators.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does rng.integers(1, 7, size=5) produce?

    The upper bound is excluded by default, like range(). Use endpoint=True to include it.
  2. 2. What is the difference between rng.shuffle(x) and rng.permutation(x)?

    shuffle mutates the array you pass. permutation leaves the original untouched and returns a new array.
  3. 3. Why is np.random.seed(0) discouraged in new code?

    The legacy functions share one global generator, so unrelated code can change each other's numbers. A Generator you create and pass around avoids that.
  4. 4. How should you create several independent random streams from one seed?

    SeedSequence.spawn derives child seeds designed to produce statistically independent streams.

Summary

  • Create a generator with rng = np.random.default_rng(seed) and pass it around.
  • A fixed seed gives the same numbers, as long as the calls happen in the same order.
  • random, integers (upper bound excluded), uniform, normal and standard_normal cover most draws; size accepts a shape.
  • choice samples with or without replacement and with optional probabilities; shuffle mutates in place and permutation returns a copy.
  • Legacy np.random.seed, rand, randn and randint use shared global state; avoid them in new code.
  • Use SeedSequence.spawn (or rng.spawn) for independent streams.

Next, draw from specific shapes of randomness in Probability Distributions and Sampling.