numpy.random.Generator.integers#

方法

random.Generator.integers(low, high=None, size=None, dtype=np.int64, endpoint=False)#

返回从 low (包含)到 high (不包含)的随机整数,如果 endpoint=True,则返回从 low (包含)到 high (包含)的随机整数。此方法取代了 RandomState.randint (endpoint=False)和 RandomState.random_integers (endpoint=True)

返回指定 dtype 的“离散均匀”分布中的随机整数。如果 high 为 None(默认值),则结果范围为 0 到 low

参数:
lowint 或整数类数组

要从分布中抽取的最小(有符号)整数(除非 high=None,在这种情况下此参数为 0,并且此值将用作 high)。

highint 或整数类数组,可选

如果提供,则表示要从分布中抽取的最大(有符号)整数之上一个值(如果 high=None,请参阅上面的行为)。如果是类数组,则必须包含整数值

sizeint 或整数元组,可选

输出形状。如果给定的形状是,例如 (m, n, k),则会抽取 m * n * k 个样本。默认值为 None,在这种情况下会返回一个单个值。

dtypedtype,可选

结果所需的 dtype。字节序必须是本机字节序。默认值为 np.int64。

endpoint布尔值,可选

如果为 true,则从区间 [low, high] 中抽样,而不是默认的 [low, high)。默认为 False

返回:
outint 或整数 ndarray

来自适当分布的 size 形状的随机整数数组,如果未提供 size,则返回单个此类随机整数。

备注

当使用 uint64 dtypes 进行广播时,最大值 (2**64) 不能表示为标准整数类型。高值数组(如果 high 为 None,则为低值)必须具有 object dtype,例如 array([2**64])。

参考文献

[1]

Daniel Lemire., “《区间内快速随机整数生成》”, ACM Transactions on Modeling and Computer Simulation 29 (1), 2019, https://arxiv.org/abs/1805.10941

示例

>>> rng = np.random.default_rng()
>>> rng.integers(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])  # random
>>> rng.integers(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

生成一个包含 0 到 4 之间整数的 2 x 4 数组

>>> rng.integers(5, size=(2, 4))
array([[4, 0, 2, 1],
       [3, 2, 2, 0]])  # random

生成一个具有 3 个不同上限的 1 x 3 数组

>>> rng.integers(1, [3, 5, 10])
array([2, 2, 9])  # random

生成一个具有 3 个不同下限的 1 x 3 数组

>>> rng.integers([1, 5, 7], 10)
array([9, 8, 7])  # random

使用 uint8 dtype 通过广播生成一个 2 x 4 数组

>>> rng.integers([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
array([[ 8,  6,  9,  7],
       [ 1, 16,  9, 12]], dtype=uint8)  # random