random Generator (NumPy)

The modern NumPy random API is built around a Generator object, created with np.random.default_rng(). You call methods on it — integers, random, normal, choice, shuffle — to produce random numbers reproducibly.

NumPy

np.random.default_rng(seed) returns a Generator that bundles a high-quality random source. You draw from it with methods like rng.integers(low, high, size) for random integers, rng.random(size) for floats in [0, 1), rng.normal() for a normal distribution, and rng.choice() to sample from an array.

This Generator interface replaces the older np.random.rand / np.random.randint global functions. The new approach is preferred because each Generator is an isolated, explicitly seeded object rather than relying on hidden global state, which makes parallel and reproducible code much safer.

Seeding the generator with a fixed integer makes the sequence deterministic, so two runs with the same seed produce identical results — essential for reproducible experiments and tests.

Syntax

rng = np.random.default_rng(seed); rng.integers(low, high, size)

Examples

Python — Same seed always yields the same numbers.

import numpy as np
rng = np.random.default_rng(42)
print(rng.integers(0, 10, 5))

Output:

[0 7 6 4 4]

Learn it in a lesson

See also

Back to the Dictionary