numpy.random.RandomState.randint#
方法
- random.RandomState.randint(low, high=None, size=None, dtype=int)#
從 low (包含) 到 high (不包含) 傳回隨機整數。
從指定 dtype 的「離散均勻」分佈的「半開」區間 [low, high) 傳回隨機整數。 如果 high 為 None (預設值),則結果來自 [0, low)。
- 參數:
- lowint 或類似陣列的 ints
從分佈中抽取的最小 (signed) 整數 (除非
high=None
,在這種情況下,此參數會比最高的此類整數大 1)。- highint 或類似陣列的 ints,選用
如果提供,則為從分佈中抽取的最大 (signed) 整數之上 1 (如果
high=None
,請參閱上方以了解行為)。 如果是類似陣列,則必須包含整數值- sizeint 或 ints 的元組,選用
輸出形狀。 如果給定的形狀為例,
(m, n, k)
,則會抽取m * n * k
個樣本。 預設值為 None,在這種情況下會傳回單一值。- dtypedtype,選用
結果的所需 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])
產生一個 2 x 4 的整數陣列,介於 0 到 4 之間 (包含)
>>> np.random.randint(5, size=(2, 4)) array([[4, 0, 2, 1], # random [3, 2, 2, 0]])
產生一個 1 x 3 的陣列,具有 3 個不同的上限
>>> np.random.randint(1, [3, 5, 10]) array([2, 2, 9]) # random
產生一個 1 x 3 的陣列,具有 3 個不同的下限
>>> np.random.randint([1, 5, 7], 10) array([9, 8, 7]) # random
使用廣播產生一個 2 x 4 的陣列,dtype 為 uint8
>>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8) array([[ 8, 6, 9, 7], # random [ 1, 16, 9, 12]], dtype=uint8)