簡體   English   中英

使用 NumPy 生成具有變量 max/min 的隨機整數序列

[英]Using NumPy to generate a sequence of random integers with variable max/min

numpy.random.uniform支持數組參數,但numpy.random.randint不支持:

import numpy as np 
two_random_uniforms = np.random.uniform([0, 1], [3, 4])
this_raises_exception = np.random.randint([0, 1], [3, 4])

我想要的第二行代碼的行為相當於:

result = []
for lown, highn in zip([0, 1], [3, 4]):
    result.append(np.random.randint(lown, highn))

有沒有辦法在不編寫 Python 循環的情況下使用變量 max/min 完成隨機整數生成? 對於我的應用程序所需的大型陣列,上述解決方法將慢得令人無法接受。 我可以在 Cython 中編寫循環,但如果可能,我寧願使用 NumPy。

您可以做的一件簡單的事情就是生成浮點數並將它們四舍五入。

def my_randint(low, high):
    return np.floor(np.random.uniform(low, high))

這是可能的這個過程可能調整所產生的分配了一下,做一些整數非常輕微比他人更容易,但除非你用密碼或其他一些敏感的應用程序時,它可能不會問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM