Random Numbers with Generator
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page targets NumPy 2.5 (2.5.4 at the time of writing), and every example was run with NumPy 2.5.4 in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. It explains how to draw random numbers with the numpy.random.Generator class, which is the interface NumPy recommends for all new code. How to make runs repeatable and how to give parallel workers independent streams has its own page, Seeding, Reproducibility & Parallel Streams. For the statistical background of the distributions see Statistics Fundamentals, and for the same ideas in R see Distributions and Random Numbers in R.
Generator, BitGenerator and default_rng
NumPy splits random number generation into two objects:
-
A bit generator produces a stream of random bits. It owns the state and the seeding logic.
PCG64is the default. -
A
Generatorwraps a bit generator and turns its bits into integers, floats and samples from distributions. All the sampling methods (random,integers,normal, …) live on theGenerator.
The normal way to build one is numpy.random.default_rng:
import numpy as np
rng = np.random.default_rng(42)
print(type(rng))
print(type(rng.bit_generator).__name__)
print(rng.random(3))
Output on NumPy 2.5.4:
<class 'numpy.random._generator.Generator'> PCG64 [0.77395605 0.43887844 0.85859792]
default_rng(seed) accepts None (fresh operating-system entropy), a non-negative integer, a sequence of integers, a SeedSequence, a BitGenerator or an existing Generator (which is returned unchanged, so a function can accept either a seed or a generator and call default_rng(arg) on it). A negative integer raises ValueError. The seed rules are covered in detail in Seeding, Reproducibility & Parallel Streams.
The recommended pattern is to create one generator at the top of a program or function and pass it down, rather than creating a new generator on every call. Creating many generators from the same small integer seed gives them identical streams.
import numpy as np
def simulate(n, rng=None):
"""Return n standard normal draws; accept a seed, a Generator or None."""
rng = np.random.default_rng(rng)
return rng.standard_normal(n)
print(simulate(3, rng=1))
shared = np.random.default_rng(1)
print(simulate(3, rng=shared))
print(simulate(3, rng=shared))
The second and third calls continue the same stream, so the third call returns different numbers from the second.
Source: NumPy: Random Generator
Which random API should I use?
The module-level functions such as np.random.seed, np.random.rand, np.random.randn and np.random.randint all use one hidden, global RandomState instance. The NumPy documentation calls this legacy interface "discouraged" for new code because shared global state makes programs hard to reason about and impossible to run safely from several threads of control.
Bit generators
NumPy ships five bit generators. All of them can be passed to Generator:
| Class | Character | Notes |
|---|---|---|
|
Default; fast, small state, good statistical quality |
Supports |
|
Newer PCG variant with a cheaper multiplier and a stronger (DXSM) output function |
Described by the NumPy documentation as having better statistical properties in parallel contexts; supports |
|
Counter-based, keyed streams |
Supports |
|
Very fast, small state |
No |
|
The Mersenne Twister, the algorithm behind the legacy |
Supports |
You rarely need anything but the default. Choose another bit generator only for a specific reason, such as reproducing an external stream (MT19937), counter-based parallelism (Philox) or a faster generator (SFC64).
import numpy as np
for bg in (np.random.PCG64, np.random.PCG64DXSM, np.random.Philox,
np.random.SFC64, np.random.MT19937):
print(bg.__name__, np.random.Generator(bg(1)).random(2))
# default_rng(42) is exactly Generator(PCG64(42))
print(np.random.Generator(np.random.PCG64(42)).random(2))
print(np.random.default_rng(42).random(2))
Output:
PCG64 [0.51182162 0.9504637 ] PCG64DXSM [0.27114667 0.27935043] Philox [0.06680201 0.07901298] SFC64 [0.99562005 0.37211968] MT19937 [0.24067554 0.72958187] [0.77395605 0.43887844] [0.77395605 0.43887844]
Different bit generators give different streams from the same seed; none of them is "more random" for ordinary data-science work. The documentation states that default_rng may change its default bit generator in a future release, with caution and advance warning, which is why code that must keep a stream forever names the bit generator explicitly.
Source: NumPy: Bit generators
Uniform floats and integers
random
rng.random(size=None, dtype=np.float64, out=None) returns floats in the half-open interval [0.0, 1.0). It supports float32 and float64 and can fill an existing array.
import numpy as np
rng = np.random.default_rng(0)
print(rng.random()) # a Python float when size is omitted
print(rng.random((2, 3)))
print(rng.random(3, dtype=np.float32).dtype)
out = np.empty(3)
rng.random(out=out) # fill an existing array, no allocation
print(out)
Source: numpy.random.Generator.random
For another interval, scale the result or use uniform: rng.uniform(low, high, size) draws from [low, high).
import numpy as np
rng = np.random.default_rng(3)
print(rng.uniform(-1, 1, size=3))
print(-1 + 2 * rng.random(3)) # equivalent in distribution
Source: numpy.random.Generator.random
integers
rng.integers(low, high=None, size=None, dtype=np.int64, endpoint=False) replaces both randint and random_integers of the legacy API. The upper bound is exclusive by default, and endpoint=True makes it inclusive, which is convenient for dice and other closed ranges. With one positional argument that argument is the exclusive upper bound, and low and high may be arrays that broadcast.
import numpy as np
rng = np.random.default_rng(42)
print(rng.integers(0, 10, size=5)) # 0 to 9
print(rng.integers(1, 6, size=5, endpoint=True)) # 1 to 5 inclusive
print(rng.integers(10, size=3)) # one argument: 0 to 9
print(rng.integers(0, 256, size=4, dtype=np.uint8)) # small integer type
print(rng.integers([1, 10], [5, 20])) # broadcast bounds
Source: numpy.random.Generator.integers
A frequent pitfall is simulating a die with rng.integers(1, 6), which never returns 6. Use rng.integers(1, 7) or endpoint=True.
Continuous distributions
Generator provides the usual families, each with size and, for float32-capable methods such as standard_normal, a dtype argument. A selection:
| Method | Distribution |
|---|---|
|
Normal; |
|
Uniform on [low, high) |
|
Exponential; |
|
Gamma and beta |
|
Log-normal; |
|
Other continuous families |
import numpy as np
rng = np.random.default_rng(42)
print(rng.standard_normal((2, 3)))
print(rng.normal(loc=10, scale=2, size=3))
print(rng.exponential(scale=2, size=3))
print(rng.lognormal(mean=0, sigma=1, size=2))
print(rng.gamma(shape=2.0, scale=1.0, size=2))
print(rng.beta(2, 5, size=2))
Because the parameters broadcast, rng.normal(loc=[0, 10, 20], scale=1) draws one value from each of three different normal distributions. scale must be non-negative; a negative value raises ValueError.
Discrete distributions
| Method | Distribution |
|---|---|
|
Number of successes in |
|
Counts with mean |
|
Trials until the first success (starts at 1) |
|
Sampling without replacement |
|
Counts over several categories |
|
Other discrete families |
import numpy as np
rng = np.random.default_rng(42)
print(rng.binomial(10, 0.5, size=5))
print(rng.poisson(3, size=5))
print(rng.geometric(0.3, size=3))
print(rng.hypergeometric(10, 5, 4, size=3))
print(rng.multinomial(10, [0.2, 0.3, 0.5]))
Multivariate distributions
multivariate_normal(mean, cov, size), dirichlet(alpha, size), multinomial and multivariate_hypergeometric return arrays with a trailing dimension for the components.
import numpy as np
rng = np.random.default_rng(42)
samples = rng.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], size=1000)
print(samples.shape)
print(np.cov(samples, rowvar=False).round(2)) # close to the requested covariance
print(rng.dirichlet([1, 1, 1])) # three non-negative numbers summing to 1
multivariate_normal factorises the covariance matrix with method="svd" by default (other options are "eigh" and "cholesky"). The documentation notes that results depend on the linear algebra library NumPy was built with, so the values may differ across builds even for the same seed. It warns when the covariance matrix is not positive semi-definite; pass check_valid="raise" to turn that into an error.
Sampling, shuffling and permutations
choice
rng.choice(a, size=None, replace=True, p=None, axis=0, shuffle=True) samples from the elements of a, or from range(a) when a is an integer.
import numpy as np
rng = np.random.default_rng(42)
a = np.arange(10)
print(rng.choice(a, size=4, replace=False)) # no repeats
print(rng.choice(["a", "b", "c"], size=5, p=[0.7, 0.2, 0.1])) # weighted, with replacement
print(rng.choice(5, size=3, replace=False, shuffle=False)) # skip the final shuffle
grid = np.arange(12).reshape(3, 4)
print(rng.choice(grid, size=2, axis=0, replace=False)) # pick whole rows
Points to remember:
-
replace=Falsecannot return more elements than the population has; it raisesValueError. -
pmust sum to 1 within a tolerance. Withreplace=Falseandp, the probabilities are applied sequentially and the result is not the same as a weighted sample with replacement. -
shuffle=Falseis faster for large samples without replacement, but the sample is then not in random order, only a random subset. -
choiceon a list converts it to an array first, so a list of mixed objects becomes a string or object array. Choose indices (rng.choice(len(items), ...)) and index the list yourself when that matters.
Source: numpy.random.Generator.choice
shuffle, permutation and permuted
-
rng.shuffle(x, axis=0)shuffles in place and returnsNone. On a multidimensional array it reorders whole slices alongaxis, so every row keeps its contents. -
rng.permutation(x, axis=0)returns a shuffled copy; an integer argument gives a permutation ofrange(n). -
rng.permuted(x, axis=None, out=None)shuffles each slice independently alongaxis. Withaxis=Noneit permutes all the elements of the array.
import numpy as np
rng = np.random.default_rng(1)
m = np.arange(12).reshape(3, 4)
p = rng.permutation(5) # a permutation of 0..4
print(p)
s = m.copy()
rng.shuffle(s, axis=1) # the same column order for every row
print(s)
print(rng.permuted(m, axis=1)) # each row shuffled independently
shuffle only changes the order of slices along one axis. To keep records aligned, for example features and labels, shuffle an index once and apply it to both arrays:
import numpy as np
rng = np.random.default_rng(0)
X = np.arange(10).reshape(5, 2)
y = np.array([0, 1, 0, 1, 0])
idx = rng.permutation(len(X))
X_shuffled, y_shuffled = X[idx], y[idx]
print(idx)
print(X_shuffled.tolist(), y_shuffled)
Source: numpy.random.Generator.permuted
dtype, out and performance options
-
random,standard_normal,standard_exponentialandstandard_gammaacceptdtype=np.float32ornp.float64and anoutarray. The float32 path is faster and uses half the memory, but the stream differs from the float64 one. -
integersaccepts any NumPy integer dtype and checks that the bounds fit it. -
Generator.standard_normal,standard_exponentialandstandard_gammause 256-step Ziggurat algorithms, which the documentation describes as 2 to 10 times faster than the older implementation inRandomState. The algorithms differ, so the same seed gives different normals, exponentials and gammas in the two APIs, and in every distribution built on them.
Generator versus the legacy API
Legacy (RandomState, np.random.*) |
Generator |
Difference |
|---|---|---|
|
|
State lives in an object, not a global |
|
|
Shape given as a tuple |
|
|
Shape given as a tuple |
|
|
Optional inclusive upper bound; more integer dtypes |
|
|
|
|
|
|
|
|
Faster algorithms |
|
|
Dictionary state |
The legacy interface remains in NumPy and is frozen: the documentation promises no further modifications to RandomState, not even to fix correctness bugs, so that old results can still be reproduced. The Generator methods may be improved in feature releases, which is the reason a Generator stream is not guaranteed to stay identical between NumPy versions. See the compatibility policy in Seeding, Reproducibility & Parallel Streams.
The legacy API in action, shown only so that old code can be recognised:
import numpy as np
rs = np.random.RandomState(42)
print(rs.randint(0, 10, 3), rs.rand(2), rs.randn(2))
np.random.seed(1) # the global generator: discouraged
print(np.random.rand(2))
Output:
[6 3 7] [0.59865848 0.15601864] [0.27904129 1.01051528] [0.417022 0.72032449]
Source: NumPy: What’s new or different
Where older tutorials are outdated
| Older statement (books and tutorials, roughly 2012 to 2019) | Current practice | Since |
|---|---|---|
|
|
|
|
|
NumPy 1.17 |
|
|
|
"The Mersenne Twister is the NumPy generator" |
PCG64 is the default of |
NumPy 1.17 |
|
|
Documented in the parallel-generation guide |
For a reproducible pipeline, also see how the same seeding choices feed into splitting and resampling in Model Evaluation and Reproducibility and MLOps Basics.
Pitfalls
-
Re-creating
default_rng(0)inside a loop or a function returns the same numbers every time. Create it once. -
rng.integers(a, b)excludesb;rng.uniform(a, b)excludesbin theory. -
normaltakes the standard deviation,lognormaltakes the mean and sigma of the log, andexponentialtakes the scale (the mean), not the rate. -
rng.random(5)is not guaranteed to equal five calls ofrng.random(), because different block sizes may use different algorithms. -
shuffleworks in place and returnsNone;x = rng.shuffle(x)setsxtoNone. -
A seed identifies a stream only for one NumPy build, machine and sequence of calls. Do not assert exact random values in unit tests; assert properties (shape, range, summary statistics) or save the arrays.