numpy.random.randint#
- random.randint(low, high=None, size=None, dtype=int)#
从 low(包含)到 high(不包含)返回随机整数。
从“离散均匀”分布中返回指定 dtype 的随机整数,范围在“半开”区间 [low, high) 内。如果 high 为 None (默认值),则结果来自 [0, low)。
- 参数:
- lowint 或 int 的数组类
从分布中抽取的最低(有符号)整数(除非
high=None,在这种情况下,此参数是一个高于最高此类整数的值)。- highint 或 int 的数组类,可选
如果提供,则为从分布中绘制的最高(有符号)整数之上一个(有关
high=None时行为的说明,请参阅上文)。如果为数组类,则必须包含整数值。- sizeint 或 int 的元组,可选
输出形状。如果给定的形状例如是
(m, n, k),则将抽取m * n * k个样本。默认为 None,在这种情况下返回单个值。- dtypedtype, optional
结果所需的 dtype。字节序必须是本机。默认值为 long。
警告
此函数默认使用 C-long dtype,在 windows 上为 32 位,在 64 位平台上为 64 位(在 32 位平台上为 32 位)。自 NumPy 2.0 起,NumPy 的默认整数在 32 位平台上为 32 位,在 64 位平台上为 64 位。这对应于 np.intp。(dtype=int 与大多数 NumPy 函数中的情况不同。)
- 返回:
另请参阅
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])
生成一个 2x4 的整数数组,范围在 0 到 4 之间(包含)。
>>> np.random.randint(5, size=(2, 4)) array([[4, 0, 2, 1], # random [3, 2, 2, 0]])
生成一个 1x3 的数组,具有 3 个不同的上限。
>>> np.random.randint(1, [3, 5, 10]) array([2, 2, 9]) # random
生成一个 1x3 的数组,具有 3 个不同的下限。
>>> np.random.randint([1, 5, 7], 10) array([9, 8, 7]) # random
使用 dtype 为 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)