Python:为什么 `random.randint(a, b)` 返回一个包含 `b` 的范围?
问题描述
random.randint(a, b)
会返回 [a, b]
范围内的整数,而不是 ,这对我来说总是很奇怪>[a, b-1]
像 range(...)
.
It has always seemed strange to me that random.randint(a, b)
would return an integer in the range [a, b]
, instead of [a, b-1]
like range(...)
.
这种明显的不一致有什么原因吗?
Is there any reason for this apparent inconsistency?
解决方案
我试图通过检查一些旧资源来了解这一点.我怀疑 randint
是在 Python 的长整数之前实现的:这意味着如果你想要一个包含 INT_MAX
的随机数,你需要调用random.randrange(0, INT_MAX + 1)
会溢出并导致参数为 (0, 0)
或 (0, INT_MIN)
取决于.
I tried to get to the bottom of this by examining some old sources. I suspected that randint
was implemented before Python's long integer: meaning that if you wanted a random number that included INT_MAX
, you would have needed to call random.randrange(0, INT_MAX + 1)
which would have overflowed and resulted in arguments of (0, 0)
or (0, INT_MIN)
depending.
但是,甚至可以追溯到 Python 1.5.2 源代码,在 Lib/whrandom.py
我们看到:
However, looking as far back as even the Python 1.5.2 sources, in Lib/whrandom.py
we see:
#
# 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.
whrandom.randint
was continued to be deprecated in 2.0, 2.1, 2.2, and 2.3; but random.randint
was marked as deprecated in 2.1, although no longer marked as deprecated in 2.2.
另外,随机2.1 版中的 .py
是 random.randint
的文档字符串中第一个要注意的:
Also, random.py
from version 2.1 is the first to note in random.randint
's 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.
"""
比这更早的唯一可用源是0.9.1 源,并且据我所知,当时还没有实现 randint
.
The only available source older than that is the 0.9.1 source, and as far as I can tell, randint
was not implemented at that point.
因此,我得出结论,randint
包括端点的推理目前只有 Guido 本人知道;鉴于 Python 2.1 的文档字符串,听起来原因可能是一个简单的错误.
Thus, I conclude that the reasoning for randint
including the endpoint is known to only Guido himself at this point; given the docstring from Python 2.1, it sounds like the reason may have been a simple mistake.
相关文章