2010-02-01 47 views
14

python的random.random()曾经返回1.0还是只返回到0.9999 ..?python的random.random()从标准库的范围

+2

在他们的丘陵中有黄金。有关random.random()返回结果的问题,请指出42分(和计数)。 <插入合适的感叹号> – telliott99

+5

注意,如果你没有终止你的序列0.9999,它实际上等于1.0。 –

回答

19

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

...随机(),它在 均匀 生成随机浮子半开区间[0.0,1.0)。

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

+8

有关括号/父范围表示法的解释,请看这里:http://en.wikipedia。 org/wiki/Interval_(数学)#Terminology –

+1

我认为当你使用Python进行编程时,Python的内部帮助系统(如另一个答案中提到的)更容易被访问。 'help(random.random)'会给OP提供他需要的信息。 – Omnifarious

+0

当你在网页上写作时,链接到真实文档要好得多。 –

10

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

但是,它可以返回0

+1

random() - > x在区间[0,1) 即包括0. – telliott99

+4

@ telliott99:这(几乎)正是我所说的。 – SLaks

+1

+1是唯一不依赖科幻数学符号的答案! –

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

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

这意味着排除1。

+9

我最喜欢你的回答。 Python有一个很棒的内部帮助系统,应该鼓励人们使用它。 – Omnifarious

11

其他答案已经明确了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.99999999999999988897769753748434595763683319091796875

+1

+1对于最大可能的浮点数! –

+1

如果上面的C代码是用-fsingle-precision-constant编译的,则可以得到1.0。详情请参阅我的回答 –

2

从锑的答案很容易看出,random.random()从来没有准确的1.0返回上有计算至少53位尾数平台的代码涉及在C中未用'f'注解的常量。这就是IEEE 754规定的精度,今天是标准。

但是,在精度较低的平台上,例如,如果在嵌入式平台上使用-fsingle-precision-constant编译Python,将b添加到* 67108864.0会导致舍入为2^53,如果b为足够接近2^26,这意味着返回1.0。请注意,无论Python的PyFloat_FromDouble函数使用什么精度,都会发生这种情况。

测试这种方法的一种方法是检查几百个随机数是否第53位是1.如果它至少有1次,这证明了足够的精度,你很好。如果不是,舍入是random.random()可以返回1.0的最可能的解释。当然可能你只是不幸。您可以通过测试更多数字来将确定性提高到您想要的水平。