Python 3の random.randint()
と NumPy の np.random.randint()
には次のような微妙だが重大な違いがあります。
random.randint(a, b)
a以上b以下の整数を1個選んで返します。以下のコードで、random.randint(3, 7)が3以上7以下の整数をランダムに生成することを確認できます。
>>> import random >>> from collections import Counter >>> Counter([random.randint(3, 7) for _ in range(1000)]) Counter({4: 206, 3: 204, 6: 201, 7: 200, 5: 189})
np.random.randint(a, b)
a以上b未満の数を1個選んで返します。
>>> import numpy as np >>> from collections import Counter >>> Counter([np.random.randint(3, 7) for _ in range(1000)]) Counter({6: 276, 3: 252, 5: 245, 4: 227})
np.random.ranom_integers(a, b) (deprecated)
deprecatedですが、かつてはこのような関数がありました。a以上b以下の整数を1個選んで返します。
>>> import numpy as np >>> from collections import Counter >>> Counter([np.random.random_integers(3, 7) for _ in range(1000)]) <stdin>:1: DeprecationWarning: This function is deprecated. Please call randint(3, 7 + 1) instead Counter({7: 214, 3: 207, 4: 194, 6: 193, 5: 192})