2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

random.randint(MIN, MAX)と、np.random.randint(MIN, MAX)は、返す値の範囲が違う

Last updated at Posted at 2021-07-26

問題になったこと

import randomrandom.randint(MIN, MAX)は、MIN以上、MAX以下を返すが、
numpynp.random.randint(MIN, MAX)は、MIN以上、MAX未満の値を返す。

MAXを含むかどうかだけの違いだが、使い所によっては致命的になることがある。(あった)

仕様上の違い

通常のrandint

https://docs.python.org/ja/3/library/random.html
random.randint(a,b)
a<=N<=bであるようなランダムな整数Nを返します。randrange(a,b+1)のエイリアスです。

npのrandint

https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html
https://note.nkmk.me/python-numpy-random/
np.random.randint()は任意の範囲の整数の乱数を返す。
引数として最小値、最大値、サイズ、および、型を渡す。サイズはタプル。
最小値以上、最大値未満の範囲の整数の乱数を返す。

実動作上の違い

簡易的な検証用コード

import random
import numpy as np

print("--- random.randint(0,1)")

for i in range (20):
 print (random.randint(0,1))

print("--- np.random.randint(0,1)")

for j in range (20):
 print (np.random.randint(0,1))

確かにrandom.randint(0,1)は0 or 1を返しているが、
np.random.randint(0,1)は0しか返さない。

$ python3 test.py
--- random.randint(0,1)
0
0
0
0
1
1
0
1
1
1
1
0
0
0
0
1
0
1
0
0
--- np.random.randint(0,1)
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

他にハマってる人いないのか?

ちょいちょいおられますね、、
結構間違え易いみたいなのでご注意下さい。。

numpyのrandintとrandomのrandintは違う
NumpyのrandintとRandomのrandintの違い
random.randint(a,b) と np.random.randint(a,b) を入れ替えると分析結果が正反対になってしまった!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?