檢視原始碼 random (stdlib v6.2)

此模組已過時。請改用 'rand' 模組。

偽隨機數生成。

此模組提供一個隨機數生成器。此方法歸功於 B.A. Wichmann 和 I.D. Hill 在 'An efficient and portable pseudo-random number generator', Journal of Applied Statistics. AS183. 1982. 以及 Byte March 1987。

此演算法是標準 Prolog 函式庫中歸功於 Richard A. O'Keefe 的版本的修改版。

每次請求隨機數時,都會使用一個狀態來計算它,並產生一個新狀態。狀態可以是隱式的(保存在進程字典中)或是一個明確的參數和返回值。在此實作中,狀態(ran/0 類型)由三個整數的元組組成。

注意

此隨機數生成器不具備密碼學上的強度。如果需要強密碼學隨機數生成器,請使用 crypto 模組中的函式之一,例如 crypto:strong_rand_bytes/1

注意

應使用改進的 rand 模組來代替此模組。

注意

某些函式使用進程字典變數 random_seed 來記住目前的種子。

如果進程在沒有先設定種子的情況下呼叫 uniform/0uniform/1,則會自動呼叫 seed/0

實作在 Erlang/OTP R15 中已變更。升級到 R15 會破壞期望特定種子產生特定輸出的應用程式。輸出仍然是確定性的數字序列,但與 R15 之前的版本相比有所不同。例如,種子 {0,0,0} 不再產生僅為零的缺陷序列。

摘要

類型

狀態。

函式

seed0() 已過時

傳回預設狀態。

seed() 已過時

在進程字典中使用預設(固定)值設定隨機數生成器的種子,並傳回舊狀態。

seed(A1, A2, A3) 已過時

在進程字典中使用整數值設定隨機數生成器的種子,並傳回舊狀態。

uniform() 已過時

傳回一個介於 0.01.0 之間均勻分佈的隨機浮點數,並更新進程字典中的狀態。

uniform(N) 已過時

對於指定的整數 N >= 1,傳回一個介於 1N 之間均勻分佈的隨機整數,並更新進程字典中的狀態。

對於指定的狀態,傳回一個介於 0.01.0 之間均勻分佈的隨機浮點數,以及一個新狀態。

對於指定的整數 N >= 1 和一個狀態,傳回一個介於 1N 之間均勻分佈的隨機整數,以及一個新狀態。

類型

-type ran() :: {integer(), integer(), integer()}.

狀態。

函式

此函式已過時。random:seed0/0 已過時;請改用 'rand' 模組。
-spec seed0() -> ran().

傳回預設狀態。

此函式已過時。random:seed/0 已過時;請改用 'rand' 模組。
-spec seed() -> ran().

在進程字典中使用預設(固定)值設定隨機數生成器的種子,並傳回舊狀態。

此函式已過時。random:seed/1 已過時;請改用 'rand' 模組。
-spec seed(SValue) -> undefined | ran()
              when SValue :: {A1, A2, A3} | integer(), A1 :: integer(), A2 :: integer(), A3 :: integer().

seed({A1, A2, A3}) 等同於 seed(A1, A2, A3)

此函式已過時。random:seed/3 已過時;請改用 'rand' 模組。
-spec seed(A1, A2, A3) -> undefined | ran() when A1 :: integer(), A2 :: integer(), A3 :: integer().

在進程字典中使用整數值設定隨機數生成器的種子,並傳回舊狀態。

以下是取得唯一值作為種子的簡單方法

random:seed(erlang:phash2([node()]),
            erlang:monotonic_time(),
            erlang:unique_integer())

詳細資訊,請參閱 erlang:phash2/1erlang:node/0erlang:monotonic_time/0erlang:unique_integer/0

此函式已過時。random:uniform/0 已過時;請改用 'rand' 模組。
-spec uniform() -> float().

傳回一個介於 0.01.0 之間均勻分佈的隨機浮點數,並更新進程字典中的狀態。

此函式已過時。random:uniform/1 已過時;請改用 'rand' 模組。
-spec uniform(N) -> pos_integer() when N :: pos_integer().

對於指定的整數 N >= 1,傳回一個介於 1N 之間均勻分佈的隨機整數,並更新進程字典中的狀態。

此函式已過時。random:uniform_s/1 已過時;請改用 'rand' 模組。
-spec uniform_s(State0) -> {float(), State1} when State0 :: ran(), State1 :: ran().

對於指定的狀態,傳回一個介於 0.01.0 之間均勻分佈的隨機浮點數,以及一個新狀態。

此函式已過時。random:uniform_s/2 已過時;請改用 'rand' 模組。
-spec uniform_s(N, State0) -> {integer(), State1}
                   when N :: pos_integer(), State0 :: ran(), State1 :: ran().

對於指定的整數 N >= 1 和一個狀態,傳回一個介於 1N 之間均勻分佈的隨機整數,以及一個新狀態。