Python标准库中random.random()的取值范围
Python里的random.random()这个函数会不会返回1.0,还是说它只会返回到0.9999..呢?
5 个回答
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));
}
这个函数实际上生成的是 m/2^53
,其中 0 <= m < 2^53
是一个整数。因为浮点数通常有53位的精度,这意味着在范围 [1/2, 1) 内,会生成所有可能的浮点数。对于接近0的值,它会跳过一些可能的浮点数值以提高效率,但生成的数字在这个范围内是均匀分布的。通过 random.random
生成的最大可能数字恰好是
0.99999999999999988897769753748434595763683319091796875
35
>>> help(random.random)
Help on built-in function random:
random(...)
random() -> x in the interval [0, 1).
这意味着1被排除在外。
24
文档在这里:http://docs.python.org/library/random.html
...random() 是一个函数,它会生成一个随机的小数,这个小数的范围是从 0.0 到 1.0,但 1.0 不包括在内。
所以,这个函数返回的值会大于或等于 0,但会小于 1.0。