python的random.random()是否会返回1.0或者只返回0.9999 ..?
Tho*_*hle 33
>>> help(random.random)
Help on built-in function random:
random(...)
random() -> x in the interval [0, 1).
Run Code Online (Sandbox Code Playgroud)
这意味着1被排除在外.
Jus*_* R. 21
文档在这里:http://docs.python.org/library/random.html
... random(),它在半开放范围[0.0,1.0]内均匀生成随机浮点数.
因此,返回值将大于或等于0,并且小于1.0.
Ant*_*ony 12
其他答案已经澄清,1不包括在范围内,但出于好奇,我决定查看来源以确切了解它是如何计算的.
可以在此处找到CPython源代码
/* random_random is the function named genrand_res53 in the original code;
* generates a random number on [0,1) with 53-bit resolution; note that
* 9007199254740992 == 2**53; I assume they're spelling "/2**53" as
* multiply-by-reciprocal in the (likely vain) hope that the compiler will
* optimize the division away at compile-time. 67108864 is 2**26. In
* effect, a contains 27 random bits shifted left 26, and b fills in the
* lower 26 bits of the 53-bit numerator.
* The orginal code credited Isaku Wada for this algorithm, 2002/01/09.
*/
static PyObject *
random_random(RandomObject *self)
{
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
Run Code Online (Sandbox Code Playgroud)
因此,功能有效地产生m/2^53
,其中0 <= m < 2^53
是一个整数.由于浮点数通常具有53位精度,这意味着在[1/2,1]范围内,会生成每个可能的浮点数.对于接近0的值,它会跳过一些可能的浮点值以提高效率,但生成的数字均匀分布在该范围内.random.random
正确生成的最大可能数量
0.99999999999999988897769753748434595763683319091796875
从 Antimony 答案中的代码很容易看出,random.random() 在至少有 53 位尾数的平台上永远不会返回精确的 1.0,用于涉及 C 中未用“f”注释的常量的计算。这是 IEEE 754 规定的精度,是今天的标准。
但是,在精度较低的平台上,例如,如果使用 -fsingle- precision-constant 编译 Python 以在嵌入式平台上使用,则将 b 添加到 a*67108864.0 可能会导致向上舍入到 2^53(如果 b 足够接近 2) ^26,这意味着返回 1.0。请注意,无论 Python 的 PyFloat_FromDouble 函数使用什么精度,都会发生这种情况。
测试这一点的一种方法是检查几百个随机数,第 53 位是否为 1。如果它至少为 1 一次,则证明足够的精度,就可以了。如果不是,舍入是最可能的解释,这意味着 random.random() 可以返回 1.0。当然也有可能你只是运气不好。您可以通过测试更多数字来将确定性提高到您想要的程度。