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。匯入
- import "math/rand/v2"
程式中的套件名稱是
rand(路徑最後的 v2 是主版本號,不是套件名,觀念見 版本管理)。常用 API
New 與 NewPCG:建立可重現的產生器
rand.New(src) 用一個來源(Source)建立 *Rand,之後透過它的方法取亂數。NewPCG(seed1, seed2) 建立 PCG 演算法的來源,兩個 uint64 就是種子。種子相同,產生的序列就相同;這是寫測試、重現 bug 時的關鍵。
注意:
*Rand 不能同時被多個 goroutine 使用,需要共用時要自己加鎖(見 互斥鎖)。套件層級函式則可安全併發使用。簽名:
- func New(src Source) *Rand
- func NewPCG(seed1, seed2 uint64) *PCG
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r1 := rand.New(rand.NewPCG(1, 2))
- r2 := rand.New(rand.NewPCG(1, 2))
- r3 := rand.New(rand.NewPCG(3, 4))
- for range 3 {
- fmt.Println(r1.IntN(100), r2.IntN(100), r3.IntN(100))
- }
- }
輸出:
- 76 76 88
- 61 61 91
- 78 78 46
前兩欄種子相同,數列完全一致;第三欄種子不同,數列也不同。
IntN、Int64N、UintN
回傳半開區間 [0, n) 內的整數,也就是 0 到 n-1。要產生 [a, b] 的整數,寫
a + r.IntN(b-a+1)。注意:n <= 0 時會 panic。
簽名:
- func (r *Rand) IntN(n int) int
- func (r *Rand) Int64N(n int64) int64
- func (r *Rand) UintN(n uint) uint
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r := rand.New(rand.NewPCG(1, 2))
- dice := make([]int, 10)
- for i := range dice {
- dice[i] = 1 + r.IntN(6)
- }
- fmt.Println("骰子:", dice)
- fmt.Println("Int64N:", r.Int64N(1_000_000_000_000))
- fmt.Println("UintN:", r.UintN(10))
- lo, hi := 50, 60
- fmt.Println("50~60:", lo+r.IntN(hi-lo+1))
- }
輸出:
- 骰子: [5 4 5 5 2 1 3 3 1 2]
- Int64N: 661916389359
- UintN: 4
- 50~60: 60
套件層級函式與 N
不想管種子時,直接呼叫套件層級的
rand.IntN、rand.Float64 等,它們使用程式啟動時隨機初始化的全域來源,每次執行結果都不同,而且可以在多個 goroutine 中同時呼叫。rand.N 是泛型函式(觀念見 泛型函式),可用於任何整數型別。最常見的用法是產生隨機時間長度,例如重試前隨機等待(jitter):rand.N(500 * time.Millisecond)。N 只有套件層級版本,*Rand 沒有對應方法。注意:n <= 0 時會 panic。
簽名:
- func IntN(n int) int
- func N[Int intType](n Int) Int
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- "time"
- )
- func main() {
- n := rand.IntN(10)
- fmt.Println("0 <= n < 10:", n >= 0 && n < 10)
- d := rand.N(500 * time.Millisecond)
- fmt.Println("d 型別是 time.Duration:", fmt.Sprintf("%T", d))
- fmt.Println("0 <= d < 500ms:", d >= 0 && d < 500*time.Millisecond)
- var b uint8 = rand.N[uint8](200)
- fmt.Println("b < 200:", b < 200)
- }
輸出:
- 0 <= n < 10: true
- d 型別是 time.Duration: time.Duration
- 0 <= d < 500ms: true
- b < 200: true
因為每次執行的值都不同,範例只印出範圍檢查的結果。
Float64
回傳 [0.0, 1.0) 之間的浮點數。常用在「以某機率發生」的判斷:
r.Float64() < 0.3 代表 30% 機率為 true。要 [a, b) 的浮點數就寫 a + r.Float64()*(b-a)。簽名:
- func (r *Rand) Float64() float64
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r := rand.New(rand.NewPCG(1, 2))
- fmt.Printf("%.4f\n", r.Float64())
- fmt.Printf("溫度: %.1f\n", 20+r.Float64()*10)
- hits := 0
- for range 10000 {
- if r.Float64() < 0.3 {
- hits++
- }
- }
- fmt.Println("10000 次中命中:", hits)
- }
輸出:
- 0.6765
- 溫度: 24.6
- 10000 次中命中: 3007
Shuffle
把序列打亂(洗牌)。
n 是元素個數,swap(i, j) 負責交換第 i 與第 j 個元素,所以任何可用索引存取的資料都能洗。注意:n < 0 時會 panic。
簽名:
- func (r *Rand) Shuffle(n int, swap func(i, j int))
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r := rand.New(rand.NewPCG(1, 2))
- cards := []string{"A", "2", "3", "4", "5", "6", "7", "8"}
- r.Shuffle(len(cards), func(i, j int) {
- cards[i], cards[j] = cards[j], cards[i]
- })
- fmt.Println(cards)
- }
輸出:
- [3 2 6 8 4 7 5 A]
Perm
回傳 [0, n) 的一個隨機排列,即 0 到 n-1 每個數字恰好出現一次、順序隨機的切片。適合「隨機決定順序」或「不重複抽出 k 個」:取
Perm(n)[:k]。簽名:
- func (r *Rand) Perm(n int) []int
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r := rand.New(rand.NewPCG(1, 2))
- fmt.Println(r.Perm(5))
- students := []string{"小明", "小華", "小美", "阿杰", "小芳", "大偉"}
- for _, i := range r.Perm(len(students))[:3] {
- fmt.Println("抽中:", students[i])
- }
- }
輸出:
- [1 4 2 0 3]
- 抽中: 小芳
- 抽中: 小美
- 抽中: 阿杰
NormFloat64
回傳標準常態分布(平均 0、標準差 1)的浮點數。要平均 μ、標準差 σ 的常態分布,寫
μ + σ*r.NormFloat64()。適合模擬身高、量測誤差這類集中在平均值附近的資料。簽名:
- func (r *Rand) NormFloat64() float64
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- r := rand.New(rand.NewPCG(1, 2))
- for range 3 {
- fmt.Printf("身高 %.1f cm\n", 170+6*r.NormFloat64())
- }
- sum := 0.0
- for range 100000 {
- sum += r.NormFloat64()
- }
- fmt.Printf("十萬次平均: %.3f\n", sum/100000)
- }
輸出:
- 身高 172.3 cm
- 身高 170.4 cm
- 身高 171.2 cm
- 十萬次平均: -0.003
NewChaCha8
ChaCha8 是另一種來源,以 32 位元組的種子建立,品質比 PCG 更強(屬於密碼學強度的演算法),套件層級函式背後用的就是它。它還有 Read 方法,可以用固定種子產生可重現的隨機位元組,例如測試用的假資料。即使如此,需要安全的隨機值時仍應使用
crypto/rand,因為固定種子本身就是可被知道的。簽名:
- func NewChaCha8(seed [32]byte) *ChaCha8
- func (c *ChaCha8) Read(p []byte) (n int, err error)
範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- )
- func main() {
- var seed [32]byte
- copy(seed[:], "fixed-seed-for-tests")
- src := rand.NewChaCha8(seed)
- r := rand.New(src)
- fmt.Println(r.IntN(1000), r.IntN(1000))
- buf := make([]byte, 8)
- n, err := rand.NewChaCha8(seed).Read(buf)
- fmt.Println(n, err)
- fmt.Printf("%x\n", buf)
- }
輸出:
- 383 110
- 8 <nil>
- 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