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 或 int 的類陣列

要從分佈中抽取的最低(帶正負號)整數(除非 high=None,在這種情況下,此參數為 0,且此值用於 high)。

highint 或 int 的類陣列,選用

如果提供,則為要從分佈中抽取的最大(帶正負號)整數之上的一個值(請參閱上面的 high=None 行為)。如果為類陣列,則必須包含整數值

sizeint 或 int 的元組,選用

輸出形狀。如果給定的形狀是例如 (m, n, k),則會抽取 m * n * k 個樣本。預設值為 None,在這種情況下,會傳回單一值。

dtypedtype,選用

結果的所需 dtype。位元組順序必須為原生。預設值為 np.int64。

endpointbool,選用

如果為 true,則從間隔 [low, high] 而非預設 [low, high) 進行取樣。預設值為 False

傳回值:
outint 或 int 的 ndarray

size 形狀的隨機整數陣列,來自適當的分佈,或者如果未提供 size,則為單一此類隨機整數。

Notes

當將廣播與 uint64 dtype 搭配使用時,最大值 (2**64) 無法表示為標準整數類型。high 陣列(或 low,如果 high 為 None)必須具有物件 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])

產生一個 2 x 4 的整數陣列,介於 0 到 4 之間,包含 0 和 4

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

產生一個 1 x 3 的陣列,具有 3 個不同的上限

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

產生一個 1 x 3 的陣列,具有 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