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. PCG64 is the default.

  • A Generator wraps a bit generator and turns its bits into integers, floats and samples from distributions. All the sampling methods (random, integers, normal, …​) live on the Generator.

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.

Which random API should I use?

flowchart TD A[Need random numbers] --> B{New code?} B -- yes --> C[rng = np.random.default_rng seed] B -- "no, must keep an old stream" --> D[np.random.RandomState seed] C --> E{Parallel workers?} E -- yes --> F[SeedSequence.spawn or rng.spawn] E -- no --> G[Pass the one Generator down] D --> H[Frozen legacy streams, no new features] A --> I[np.random.seed, np.random.rand ...] I --> J[Discouraged: hidden global RandomState]

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

PCG64

Default; fast, small state, good statistical quality

Supports jumped() and advance()

PCG64DXSM

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 jumped() and advance()

Philox

Counter-based, keyed streams

Supports jumped() and advance(); suited to massively parallel work

SFC64

Very fast, small state

No jumped()

MT19937

The Mersenne Twister, the algorithm behind the legacy RandomState

Supports jumped(); larger state, slower

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.

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)

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

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

A frequent pitfall is simulating a die with rng.integers(1, 6), which never returns 6. Use rng.integers(1, 7) or endpoint=True.

bytes

rng.bytes(length) returns random bytes. It is a convenient source of reproducible test data but it is not a source of cryptographic secrets; use Python’s secrets module for tokens and keys.

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

standard_normal(size) / normal(loc, scale, size)

Normal; normal takes the mean and the standard deviation (not the variance)

uniform(low, high, size)

Uniform on [low, high)

exponential(scale, size)

Exponential; scale is 1 / rate

gamma(shape, scale, size), beta(a, b, size)

Gamma and beta

lognormal(mean, sigma, size)

Log-normal; mean and sigma are of the underlying normal

laplace, logistic, gumbel, weibull, pareto, rayleigh, standard_t, chisquare, f, vonmises

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

binomial(n, p, size)

Number of successes in n trials

poisson(lam, size)

Counts with mean lam

geometric(p, size)

Trials until the first success (starts at 1)

hypergeometric(ngood, nbad, nsample, size)

Sampling without replacement

multinomial(n, pvals, size)

Counts over several categories

negative_binomial, zipf, logseries

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=False cannot return more elements than the population has; it raises ValueError.

  • p must sum to 1 within a tolerance. With replace=False and p, the probabilities are applied sequentially and the result is not the same as a weighted sample with replacement.

  • shuffle=False is faster for large samples without replacement, but the sample is then not in random order, only a random subset.

  • choice on 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.

shuffle, permutation and permuted

  • rng.shuffle(x, axis=0) shuffles in place and returns None. On a multidimensional array it reorders whole slices along axis, so every row keeps its contents.

  • rng.permutation(x, axis=0) returns a shuffled copy; an integer argument gives a permutation of range(n).

  • rng.permuted(x, axis=None, out=None) shuffles each slice independently along axis. With axis=None it 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)

dtype, out and performance options

  • random, standard_normal, standard_exponential and standard_gamma accept dtype=np.float32 or np.float64 and an out array. The float32 path is faster and uses half the memory, but the stream differs from the float64 one.

  • integers accepts any NumPy integer dtype and checks that the bounds fit it.

  • Generator.standard_normal, standard_exponential and standard_gamma use 256-step Ziggurat algorithms, which the documentation describes as 2 to 10 times faster than the older implementation in RandomState. 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

np.random.seed(n)

default_rng(n)

State lives in an object, not a global

rand(d0, d1), random_sample(size)

random(size)

Shape given as a tuple

randn(d0, d1)

standard_normal(size)

Shape given as a tuple

randint(low, high)

integers(low, high, endpoint=...)

Optional inclusive upper bound; more integer dtypes

random_integers (deprecated)

integers(..., endpoint=True)

shuffle(x), permutation(x)

shuffle, permutation, permuted

axis support on shuffle, permutation and choice

choice(..., replace=False)

choice(..., replace=False, shuffle=...)

Faster algorithms

RandomState.get_state

bit_generator.state

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]

Where older tutorials are outdated

Older statement (books and tutorials, roughly 2012 to 2019) Current practice Since

np.random.seed(0) at the top of a script, then np.random.rand and np.random.randn

rng = np.random.default_rng(0) and rng.random, rng.standard_normal

Generator introduced in NumPy 1.17 (2019); documentation now discourages the global API

np.random.randint(1, 7)

rng.integers(1, 7) or rng.integers(1, 6, endpoint=True)

NumPy 1.17

np.random.random_integers(1, 6)

rng.integers(1, 6, endpoint=True)

random_integers deprecated

"The Mersenne Twister is the NumPy generator"

PCG64 is the default of default_rng

NumPy 1.17

np.random.seed(seed + worker_id) for workers

SeedSequence.spawn

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) excludes b; rng.uniform(a, b) excludes b in theory.

  • normal takes the standard deviation, lognormal takes the mean and sigma of the log, and exponential takes the scale (the mean), not the rate.

  • rng.random(5) is not guaranteed to equal five calls of rng.random(), because different block sizes may use different algorithms.

  • shuffle works in place and returns None; x = rng.shuffle(x) sets x to None.

  • 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.