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。
---------------------