1. 程式人生 > >golang隨機數生成踩過的坑記錄一下

golang隨機數生成踩過的坑記錄一下

不廢話了,直接上程式碼:

package main

import (
"fmt"
"math/rand"
)

func main() {
fmt.Println(rand.Intn(100))
fmt.Println(rand.Intn(100))
}

 

執行測試一下,
$ go run rand.go
81
87

OK,看似沒問題,但再執行一次看看:

$ go run rand.go
81
87

輸出的結果完全一樣,檢視官網上的例子:

package main

import (
"fmt"
"math/rand"
)

func main() {
rand.Seed(
42) // Try changing this number! 注意,注意,注意,重要的事情說三遍 answers := []string{ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now
", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", } fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))]) }

 

我這邊執行輸出如下:
Magic 8-Ball says: As I see it yes
多執行幾次,輸出結果不變。按照註釋中說的,修改rand.Seed(42),隨便改這裡的值:rand.Seed(2),結果如下:
Magic 8-Ball says: Most likely
多執行幾次還是不變,所以關鍵在rand.Seed()這裡,檢視文件:
func (r *Rand) Seed(seed int64)
Seed uses the provided seed value to initialize the generator to a deterministic state.
Seed使用提供的seed值將發生器初始化為確定性狀態。不是很理解這句話的意思,修改一下一開始的程式碼試試:

package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
rand.Seed(time.Now().Unix())
fmt.Println(rand.Intn(100))
fmt.Println(rand.Intn(100))
}

$ go run rand.go

9
46
$ go run rand.go
78
98


OK,每次執行產生的輸出不一樣了。

幾點注意項:

1、如果不使用rand.Seed(seed int64),每次執行,得到的隨機數會一樣,程式不停止,一直獲取的隨機數是不一樣的;

2、每次執行時rand.Seed(seed int64),seed的值要不一樣,這樣生成的隨機數才會和上次執行時生成的隨機數不一樣;

3、rand.Intn(n int)得到的隨機數int i,0 <= i < n。
---------------------