为什么这会重复相同的随机数? [英] Why this repeats the same random number?
问题描述
我是 Go 的新手,不知道为什么每次运行都会为 rand.Intn(n int) int
打印相同的数字:
I'm new to Go and not sure why it prints the same number for rand.Intn(n int) int
for every run:
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Intn(10))
}
文档说:
Intn 从默认 Source 返回 [0,n) 中的非负伪随机数作为 int 值.如果 n <= 0,它会发生恐慌.
Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.
我该如何正确播种随机数生成?
And how do I properly seed the random number generation?
推荐答案
通过调用rand.Seed()
函数,向它传递一个(随机)种子(通常是当前的 unix 时间戳).引用 math/rand
包文档:
By calling the rand.Seed()
function, passing it a (random) seed (typically the current unix timestamp). Quoting from math/rand
package doc:
顶级函数,例如 Float64 和 Int,使用默认的共享源,该源在每次程序运行时生成确定性的值序列.如果每次运行需要不同的行为,请使用 Seed 函数来初始化默认 Source.
Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.
示例:
rand.Seed(time.Now().UnixNano())
如果 rand.Seed()
没有被调用,生成器的行为就像是 1 种子:
If rand.Seed()
is not called, the generator behaves as if seeded by 1:
Seed 使用提供的种子值将默认 Source 初始化为确定性状态.如果没有调用 Seed,则生成器的行为就像由 Seed(1) 播种一样.
Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1).
这篇关于为什么这会重复相同的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!