Bounded discrete sampling
Simulating dice, indexes, or categorical labels within a bounded integer range.
NumPy · Function
Generates random integers from a discrete uniform distribution over a half-open interval. Supply one bound for values in [0, low), or two bounds for values in [low, high).
The function samples integers from a discrete uniform distribution. With both bounds supplied, values are at least low and strictly less than high; when high is omitted, low acts as the exclusive upper bound and zero is the lower bound. The size argument controls whether the result is scalar or an array, while dtype selects the integer type.
numpy.random.randint(low, high=None, size=None, dtype=int)| Name | Type | Description |
|---|---|---|
low | int or array-like of ints | Lower bound of the interval; included when high is supplied. If high is omitted, this is the exclusive upper bound and the lower bound is zero. |
high | int or array-like of ints, optional | Optional exclusive upper bound. If omitted, sampling uses the interval [0, low). |
size | int or tuple of ints, optional | Optional output shape. None returns a scalar; an integer or tuple of integers requests an array. |
dtype | dtype, optional | Optional dtype of the generated integers; defaults to int. |
An integer when size is None, otherwise an ndarray of random integers with the requested size and dtype.
import numpy as np
samples = np.random.randint(1, 7, size=(2, 4), dtype=np.int64)
print(samples)
# Every value is an integer from 1 through 6.Creates an array of eight random six-sided-die values arranged as two rows of four.
Simulating dice, indexes, or categorical labels within a bounded integer range.
Creating reproducible-shape test fixtures or synthetic integer matrices.
Selecting random positions or IDs when the valid domain is represented by consecutive integers.
It samples from a discrete uniform distribution over a half-open interval. With high provided, the interval is [low, high); without it, the interval is [0, low).
Follow-up: How would you generate values in an inclusive interval [a, b]? Use np.random.randint(a, b + 1), provided b + 1 is valid for the chosen integer dtype.
size may be an integer or a tuple of integers. An integer produces a one-dimensional array of that length, a tuple produces that shape, and None returns one random integer.
Follow-up: What determines the number of samples for size=(m, n, k)? The product m*n*k.
dtype specifies the desired result dtype and defaults to int. The returned value is either a single integer or an array whose shape follows size.
Follow-up: Why might dtype matter? It controls the integer representation and therefore the range and storage characteristics of the result.
numpy.random.Generator.integersnumpy.random.random_integersnumpy.random.choicenumpy.random.uniform