簡體   English   中英

在python中,random.uniform()和random.random()有什么區別?

[英]In python, what is the difference between random.uniform() and random.random()?

在隨機模塊的python中, random.uniform()random.random()什么區別? 它們都生成偽隨機數, random.uniform()從均勻分布生成數字, random.random()生成下一個隨機數。 有什么不同?

random.random()為您提供[0.0, 1.0)范圍內的隨機浮點數(因此包括0.0 ,但不包括1.0 ,也稱為半開放范圍)。 random.uniform(a, b)給出一個[a, b]范圍內的隨機浮點數(其中舍入可能最終給你b )。

random.uniform()實現直接使用random.random()

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()

random.uniform(0, 1)random.random()基本相同( 1.0 最接近1.0浮點值仍然會給你最接近1.0浮點值,那里不存在舍入誤差)。

random.random()中 ,輸出介於0和1之間,並且它不需要輸入參數

random.uniform()接受參數,其中您可以提交隨機數的范圍。 例如
import random as ra print ra.random() print ra.uniform(5,10)

輸出: -
0.672485369423 7.9237539416

不同之處在於論點。 從[ random.random()范圍內的均勻分布生成隨機數是很常見的,所以random.random()就是這樣做的。 使用random.uniform(a, b)指定不同的范圍。

根據random.uniform上的文檔:

返回隨機浮點數N,使得對於<= b,a <= N <= b,對於b <a,b <= N <= a。

random.random

返回[0.0,1.0]范圍內的下一個隨機浮點數。

即使用random.uniform您可以指定從中繪制偽隨機數的范圍,例如在3和10之間。使用random.random您將獲得介於0和1之間的數字。

除了上面提到的內容之外, .uniform()也可以用於生成具有所需形狀的多個隨機數,這是.random()無法實現的。

np.random.seed(99)
np.random.random()

#generates 0.6722785586307918

而以下代碼

np.random.seed(99)
np.random.uniform(0.0, 1.0, size = (5,2))

#generates this 
array([[0.67227856, 0.4880784 ],
       [0.82549517, 0.03144639],
       [0.80804996, 0.56561742],
       [0.2976225 , 0.04669572],
       [0.9906274 , 0.00682573]])

這不能用隨機(...)來完成,如果你為ML相關的東西生成隨機(...)數字,大多數時候,你最終會使用.uniform(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM