LoginSignup
59
31

More than 5 years have passed since last update.

randintに気をつけよう

Posted at

Pythonのrandintでハマったのメモ。
ある区間内のランダムな整数を返す関数として、random.randintとnumpy.random.randintがありますが、これら実は仕様が違います。

ドキュメントを見てみましょう。まずはrandom.randintから

randint(self, a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.

次にnumpy.random.randint

randint(low, high=None, size=None)

Return random integers from low (inclusive) to high (exclusive).

Return random integers from the "discrete uniform" distribution in the
"half-open" interval [low, high). If high is None (the default),
then results are from [0, low).

つまりrandom.randint(a,b)はaからbまでの整数(bを含む)が返ってくる可能性があり、numpy.random.randint(a,b)はaからb-1までの整数が返ってくる可能性があるんですね。

なんじゃこりゃあああ!紛らわしい!

どっちが自然な仕様かというと後者だと思います。例えば、range(1,5)は[1,2,3,4]が返ってくるし。

では、Happy Halloween and Happy Hacking!

59
31
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
59
31