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

dan*_*els 16 python random

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被排除在外.

  • 我最喜欢你的答案.Python有一个很棒的内部帮助系统,应该鼓励人们使用它. (10认同)

Jus*_* R. 21

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

... random(),它在半开放范围[0.0,1.0]内均匀生成随机浮点数.

因此,返回值将大于或等于0,并且小于1.0.

  • 有关括号/父范围表示法的解释,请查看此处:http://en.wikipedia.org/wiki/Interval_(Mathematics )#Terminology (8认同)
  • 我认为当你用 Python 编程时,Python 的内部帮助系统(如另一个答案中提到的)更容易立即访问。`help(random.random)` 将为 OP 提供他需要的信息。 (2认同)

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

  • 如果上面的C代码是用-fsingle-precision-constant编译的,那么这可能会产生1.0.详情请见我的回答 (2认同)

SLa*_*aks 10

Python的random.random函数返回小于但不等于的数字1.

但是,它可以返回0.

  • @ telliott99:那几乎就是我所说的. (4认同)

Joa*_*ner 5

从 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。当然也有可能你只是运气不好。您可以通过测试更多数字来将确定性提高到您想要的程度。