numpy.random.RandomState.randint#

方法

random.RandomState.randint(low, high=None, size=None, dtype=int)#

返回从 low(包含)到 high(不包含)的随机整数。

返回从指定 dtype 的“离散均匀”分布中,在“半开”区间 [low, high) 内的随机整数。如果 high 为 None(默认值),则结果将从 [0, low) 中生成。

注意

新代码应改用 Generator 实例的 integers 方法;请参阅快速入门

参数:
lowint 或 整数数组型对象

要从分布中抽取的最低(有符号)整数(除非 high=None,在这种情况下,此参数是此类最高整数加一)。

highint 或 整数数组型对象, 可选

如果提供,则表示要从分布中抽取的最大(有符号)整数加一(有关 high=None 时的行为,请参见上文)。如果是数组型对象,则必须包含整数值。

sizeint 或 整数元组, 可选

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

dtypedtype, 可选

结果的期望数据类型。字节顺序必须是本地字节序。默认值为 long。

警告

此函数默认使用 C-long 数据类型,在 Windows 上为 32 位,在 64 位平台上为 64 位(在 32 位平台上为 32 位)。从 NumPy 2.0 开始,NumPy 的默认整数在 32 位平台上为 32 位,在 64 位平台上为 64 位。这对应于 np.intp。(dtype=int 与大多数 NumPy 函数中的情况不同。)

返回:
outint 或 int 的 ndarray

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

另请参阅

random_integers

类似于 randint,但适用于闭区间 [low, high],如果省略 high,则 1 是最低值。

random.Generator.integers

应在新代码中使用。

示例

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

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

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

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

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

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

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

使用广播和 uint8 数据类型生成一个 2x4 数组

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