Python:为什么`random.randint(a,b)`返回一个包含`b`的范围? [英] Python: why does `random.randint(a, b)` return a range inclusive of `b`?

查看:197
本文介绍了Python:为什么`random.randint(a,b)`返回一个包含`b`的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,random.randint(a, b)会返回一个在[a, b]范围内的整数,而不是像range(...)这样的[a, b-1].

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.

此外, random.py来自版本2.1 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.

因此,我得出结论,此时,只有Guido本人知道randint 包括端点的推理;给定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.

这篇关于Python:为什么`random.randint(a,b)`返回一个包含`b`的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆