标准库中python的random.random()的范围

2024-04-19 21:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

文件在这里:http://docs.python.org/library/random.html

...random(), which generates a random float uniformly in the semi-open range [0.0, 1.0).

因此,返回值将大于或等于0,小于1.0。

其他的答案已经澄清了1不在范围之内,但是出于好奇,我决定看看源代码,看看它是如何精确计算的。

可以找到CPython源here

/* 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.999999999999988897769753748434595763683319091796875

>>> help(random.random)
Help on built-in function random:

random(...)
    random() -> x in the interval [0, 1).

这意味着1被排除在外。

相关问题 更多 >