2010-02-01 99 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的最可能的解釋。當然可能你只是不幸。您可以通過測試更多數字來將確定性提高到您想要的水平。