[pkg] math/rand
math
Pow
回傳 x 的 y 次方:
// func Pow(x, y float64) float64
math/rand
產生隨機整數
在 Go 中,可以透過 rand.Intn 這個方法來產生隨機的正整數。自 Go 1.20 起,全域的 math/rand 函式已自動使用隨機種子,不再需要手動呼叫 rand.Seed()。Go 1.22 更新增了 math/rand/v2 套件 。以下是舊版(Go 1.19 以前)需要手動設定種子的做法:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// STEP 1:透過 NewSource 方法,每次搭配不同的 seed 產生新的 source
seed := time.Now().UnixNano()
source := rand.NewSource(seed)
// STEP 2:透過 New 方法帶有不同 seed 的 rand 方法
r := rand.New(source)
// STEP 3:透過 Intn 方法隨機產生正整數
fmt.Println("random number", r.Intn(10))
}