可以random.randint(1,10)返回11吗? [英] Could random.randint(1,10) ever return 11?

查看:922
本文介绍了可以random.randint(1,10)返回11吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究此问题并阅读random.py中的源代码时,我开始怀疑randrangerandint确实表现得像广告宣传"一样.我非常愿意相信这一点,但是按照我的理解,randrange本质上实现为

When researching for this question and reading the sourcecode in random.py, I started wondering whether randrange and randint really behave as "advertised". I am very much inclined to believe so, but the way I read it, randrange is essentially implemented as

start + int(random.random()*(stop-start))

(假设startstop为整数值),所以randrange(1, 10)应该返回1到9之间的随机数.

(assuming integer values for start and stop), so randrange(1, 10) should return a random number between 1 and 9.

randint(start, stop)正在调用randrange(start, stop+1),从而返回1到10之间的数字.

randint(start, stop) is calling randrange(start, stop+1), thereby returning a number between 1 and 10.

我的问题是:

如果random()曾经返回1.0,那么randint(1,10)将会返回11,不是吗?

If random() were ever to return 1.0, then randint(1,10) would return 11, wouldn't it?

推荐答案

来自random.py和文档:

"""Get the next random number in the range [0.0, 1.0)."""

)表示间隔为排他 1.0.也就是说,它将永远不会返回1.0.

The ) indicates that the interval is exclusive 1.0. That is, it will never return 1.0.

这是数学上的常规约定,[]是包括在内的,而()是排斥的,并且两种类型的括号可以作为(a, b][a, b)混合使用.请参阅维基百科:时间间隔(数学)进行正式说明.

This is a general convention in mathematics, [ and ] is inclusive, while ( and ) is exclusive, and the two types of parenthesis can be mixed as (a, b] or [a, b). Have a look at wikipedia: Interval (mathematics) for a formal explanation.

这篇关于可以random.randint(1,10)返回11吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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