math/rand/v2

最後更新


math/rand/v2 套件產生偽亂數(pseudo-random number),用於模擬、遊戲、抽樣、測試資料等不涉及安全的場合。

這個套件做什麼


偽亂數是用演算法算出來、「看起來」隨機的數列。給定相同的起始值(種子,seed),就會產生完全相同的數列。這個特性很有用:測試或模擬時可以用固定種子讓結果可重現。
Go 1.22 起提供 math/rand/v2,取代舊的 math/rand。新版的主要差異:
項目math/rand/v2
套件層級函式(rand.IntN 等)每次程式啟動自動以隨機種子初始化,不能也不需要設定種子
想要可重現的序列自己建立 rand.New(rand.NewPCG(s1, s2))
範圍函式命名IntN、Int64N、UintN(舊版叫 Intn、Int63n)
泛型rand.N 可用於任何整數型別,包含 time.Duration
演算法提供 PCG 與 ChaCha8 兩種來源

注意:這個套件的輸出可被預測,不能用來產生密碼、權杖(token)、金鑰。安全用途請用 crypto/rand。
和相近套件的差別:舊版 math/rand 的 Seed、Read 已被標記為 Deprecated,新程式直接用 v2。

匯入


  1. import "math/rand/v2"

程式中的套件名稱是 rand(路徑最後的 v2 是主版本號,不是套件名,觀念見 版本管理)。

常用 API


New 與 NewPCG:建立可重現的產生器


rand.New(src) 用一個來源(Source)建立 *Rand,之後透過它的方法取亂數。NewPCG(seed1, seed2) 建立 PCG 演算法的來源,兩個 uint64 就是種子。
種子相同,產生的序列就相同;這是寫測試、重現 bug 時的關鍵。
注意:*Rand 不能同時被多個 goroutine 使用,需要共用時要自己加鎖(見 互斥鎖)。套件層級函式則可安全併發使用。
簽名:
  1. func New(src Source) *Rand
  2. func NewPCG(seed1, seed2 uint64) *PCG

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r1 := rand.New(rand.NewPCG(1, 2))
  8. r2 := rand.New(rand.NewPCG(1, 2))
  9. r3 := rand.New(rand.NewPCG(3, 4))
  10. for range 3 {
  11. fmt.Println(r1.IntN(100), r2.IntN(100), r3.IntN(100))
  12. }
  13. }

輸出:
  1. 76 76 88
  2. 61 61 91
  3. 78 78 46

前兩欄種子相同,數列完全一致;第三欄種子不同,數列也不同。

IntN、Int64N、UintN


回傳半開區間 [0, n) 內的整數,也就是 0 到 n-1。要產生 [a, b] 的整數,寫 a + r.IntN(b-a+1)。
注意:n <= 0 時會 panic。
簽名:
  1. func (r *Rand) IntN(n int) int
  2. func (r *Rand) Int64N(n int64) int64
  3. func (r *Rand) UintN(n uint) uint

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. dice := make([]int, 10)
  9. for i := range dice {
  10. dice[i] = 1 + r.IntN(6)
  11. }
  12. fmt.Println("骰子:", dice)
  13. fmt.Println("Int64N:", r.Int64N(1_000_000_000_000))
  14. fmt.Println("UintN:", r.UintN(10))
  15. lo, hi := 50, 60
  16. fmt.Println("50~60:", lo+r.IntN(hi-lo+1))
  17. }

輸出:
  1. 骰子: [5 4 5 5 2 1 3 3 1 2]
  2. Int64N: 661916389359
  3. UintN: 4
  4. 50~60: 60

套件層級函式與 N


不想管種子時,直接呼叫套件層級的 rand.IntN、rand.Float64 等,它們使用程式啟動時隨機初始化的全域來源,每次執行結果都不同,而且可以在多個 goroutine 中同時呼叫。
rand.N 是泛型函式(觀念見 泛型函式),可用於任何整數型別。最常見的用法是產生隨機時間長度,例如重試前隨機等待(jitter):rand.N(500 * time.Millisecond)。N 只有套件層級版本,*Rand 沒有對應方法。
注意:n <= 0 時會 panic。
簽名:
  1. func IntN(n int) int
  2. func N[Int intType](n Int) Int

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. "time"
  6. )
  7. func main() {
  8. n := rand.IntN(10)
  9. fmt.Println("0 <= n < 10:", n >= 0 && n < 10)
  10. d := rand.N(500 * time.Millisecond)
  11. fmt.Println("d 型別是 time.Duration:", fmt.Sprintf("%T", d))
  12. fmt.Println("0 <= d < 500ms:", d >= 0 && d < 500*time.Millisecond)
  13. var b uint8 = rand.N[uint8](200)
  14. fmt.Println("b < 200:", b < 200)
  15. }

輸出:
  1. 0 <= n < 10: true
  2. d 型別是 time.Duration: time.Duration
  3. 0 <= d < 500ms: true
  4. b < 200: true

因為每次執行的值都不同,範例只印出範圍檢查的結果。

Float64


回傳 [0.0, 1.0) 之間的浮點數。常用在「以某機率發生」的判斷:r.Float64() < 0.3 代表 30% 機率為 true。要 [a, b) 的浮點數就寫 a + r.Float64()*(b-a)。
簽名:
  1. func (r *Rand) Float64() float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. fmt.Printf("%.4f\n", r.Float64())
  9. fmt.Printf("溫度: %.1f\n", 20+r.Float64()*10)
  10. hits := 0
  11. for range 10000 {
  12. if r.Float64() < 0.3 {
  13. hits++
  14. }
  15. }
  16. fmt.Println("10000 次中命中:", hits)
  17. }

輸出:
  1. 0.6765
  2. 溫度: 24.6
  3. 10000 次中命中: 3007

Shuffle


把序列打亂(洗牌)。n 是元素個數,swap(i, j) 負責交換第 i 與第 j 個元素,所以任何可用索引存取的資料都能洗。
注意:n < 0 時會 panic。
簽名:
  1. func (r *Rand) Shuffle(n int, swap func(i, j int))

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. cards := []string{"A", "2", "3", "4", "5", "6", "7", "8"}
  9. r.Shuffle(len(cards), func(i, j int) {
  10. cards[i], cards[j] = cards[j], cards[i]
  11. })
  12. fmt.Println(cards)
  13. }

輸出:
  1. [3 2 6 8 4 7 5 A]

Perm


回傳 [0, n) 的一個隨機排列,即 0 到 n-1 每個數字恰好出現一次、順序隨機的切片。適合「隨機決定順序」或「不重複抽出 k 個」:取 Perm(n)[:k]。
簽名:
  1. func (r *Rand) Perm(n int) []int

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. fmt.Println(r.Perm(5))
  9. students := []string{"小明", "小華", "小美", "阿杰", "小芳", "大偉"}
  10. for _, i := range r.Perm(len(students))[:3] {
  11. fmt.Println("抽中:", students[i])
  12. }
  13. }

輸出:
  1. [1 4 2 0 3]
  2. 抽中: 小芳
  3. 抽中: 小美
  4. 抽中: 阿杰

NormFloat64


回傳標準常態分布(平均 0、標準差 1)的浮點數。要平均 μ、標準差 σ 的常態分布,寫 μ + σ*r.NormFloat64()。適合模擬身高、量測誤差這類集中在平均值附近的資料。
簽名:
  1. func (r *Rand) NormFloat64() float64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. for range 3 {
  9. fmt.Printf("身高 %.1f cm\n", 170+6*r.NormFloat64())
  10. }
  11. sum := 0.0
  12. for range 100000 {
  13. sum += r.NormFloat64()
  14. }
  15. fmt.Printf("十萬次平均: %.3f\n", sum/100000)
  16. }

輸出:
  1. 身高 172.3 cm
  2. 身高 170.4 cm
  3. 身高 171.2 cm
  4. 十萬次平均: -0.003

NewChaCha8


ChaCha8 是另一種來源,以 32 位元組的種子建立,品質比 PCG 更強(屬於密碼學強度的演算法),套件層級函式背後用的就是它。它還有 Read 方法,可以用固定種子產生可重現的隨機位元組,例如測試用的假資料。
即使如此,需要安全的隨機值時仍應使用 crypto/rand,因為固定種子本身就是可被知道的。
簽名:
  1. func NewChaCha8(seed [32]byte) *ChaCha8
  2. func (c *ChaCha8) Read(p []byte) (n int, err error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. var seed [32]byte
  8. copy(seed[:], "fixed-seed-for-tests")
  9. src := rand.NewChaCha8(seed)
  10. r := rand.New(src)
  11. fmt.Println(r.IntN(1000), r.IntN(1000))
  12. buf := make([]byte, 8)
  13. n, err := rand.NewChaCha8(seed).Read(buf)
  14. fmt.Println(n, err)
  15. fmt.Printf("%x\n", buf)
  16. }

輸出:
  1. 383 110
  2. 8 <nil>
  3. 8d8f04bc0a9d4962

重點整理


  • 新程式用 math/rand/v2(Go 1.22 起),套件名是 rand
  • 套件層級函式自動隨機初始化、可併發使用;要可重現就用 rand.New(rand.NewPCG(s1, s2))
  • IntN(n) 回傳 [0, n),n <= 0 會 panic;rand.N 是泛型版,可直接產生 time.Duration
  • 洗牌用 Shuffle,不重複抽樣用 Perm(n)[:k]
  • *Rand 不可併發共用
  • 密碼、權杖、金鑰一律用 crypto/rand

資料來源