random.randint(a, b)
会返回 [a, b]
范围内的整数,而不是 ,这对我来说总是很奇怪>[a, b-1]
像 range(...)
.
这种明显的不一致有什么原因吗?
最佳答案
我试图通过检查一些旧资料来了解这一点。我怀疑 randint
是在 Python 的长整数之前实现的:这意味着如果你想要一个包含 INT_MAX
的随机数,你需要调用random.randrange(0, INT_MAX + 1)
会溢出并导致参数为 (0, 0)
或 (0, INT_MIN)
取决于。
但是,甚至可以追溯到 the Python 1.5.2 sources ,在 Lib/whrandom.py
我们看到:
#
# Get a random integer in the range [a, b] including both end points.
# (Deprecated; use randrange below.)
#
def randint(self, a, b):
return self.randrange(a, b+1)
whrandom.randint
在 2.0 中继续被弃用, 2.1 , 2.2 , 和 2.3 ;但是 random.randint
在 2.1 中被标记为已弃用,尽管在 2.2 中不再标记为已弃用.
另外,random.py
from version 2.1是 random.randint
的 docstring 中第一个要注意的:
def randrange(self, start, stop=None, step=1, int=int, default=None):
"""Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
Do not supply the 'int' and 'default' arguments.
"""
唯一比这更早的可用来源是 the 0.9.1 source ,据我所知,当时还没有实现 randint
。
因此,我得出结论,randint
包括端点的推理目前只有 Guido 本人知道;鉴于 Python 2.1 的文档字符串,听起来原因可能是一个简单的错误。
关于Python:为什么 `random.randint(a, b)` 返回一个包含 `b` 的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2568783/