jon*_*101 7 random numbers generator seed go
Go的官方浏览在沙盒中提供了以下代码:
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("My favorite number is", rand.Intn(10))
}
Run Code Online (Sandbox Code Playgroud)
而此指令:
注意:执行这些程序的环境是确定性的,因此,每次运行示例程序rand.Intn都会返回相同的数字。(要查看其他数字,请为数字生成器添加种子;请参阅rand.Seed。)
阅读rand.Seed官方文档下的条目并阅读此答案后,我仍然无法正确植入随机数生成器。
有人可以演示如何使用rand.Seed函数为随机数生成器生成种子吗?
非常感谢,乔恩
默认情况下rand.Intn
使用globalRand.Intn。它是内部创建的,请参见此处。因此,当您通过rand.Seed进行设置时
rand.Seed(time.Now().UTC().UnixNano())
Run Code Online (Sandbox Code Playgroud)
然后globalRand
使用新的种子值。
需要时,您可以创建具有种子值的自己的rand生成器。请参阅godoc示例。
播放链接(无种子):https : //play.golang.org/p/2yg7xjvHoJ
输出:
My favorite number is 1
My favorite number is 7
My favorite number is 7
My favorite number is 9
My favorite number is 1
My favorite number is 8
My favorite number is 5
My favorite number is 0
My favorite number is 6
Run Code Online (Sandbox Code Playgroud)
播放链接(带有种子):https : //play.golang.org/p/EpW6R5rvM4
输出:
My favorite number is 0
My favorite number is 8
My favorite number is 7
My favorite number is 2
My favorite number is 3
My favorite number is 9
My favorite number is 4
My favorite number is 7
My favorite number is 8
Run Code Online (Sandbox Code Playgroud)
编辑:
如@AlexanderTrakhimenok所述,在操场上程序的执行是deterministic
。但是,游乐场不会阻止您提供rand.Seed
价值。
请记住,种子值是int64
。
当你rand.Intn
,它使用默认的种子值1
的globalRand
。
var globalRand = New(&lockedSource{src: NewSource(1).(Source64)})
Run Code Online (Sandbox Code Playgroud)
自从以来,在操场上time.Now().UTC().UnixNano()
给你一样的价值。但这与默认种子值不同,这就是为什么第二个游乐场链接产生不同结果的原因。1257894000000000000
the start time is locked to a constant
因此,以上两个总是会产生相同的结果。
我们应该如何在运动场中更改结果?
我们可以。让我们的供应UnixNano()
值1500909006430687579
来rand.Seed
,这是从我的机器产生。
播放链接:https : //play.golang.org/p/-nTydej8YF
输出:
My favorite number is 3
My favorite number is 5
My favorite number is 3
My favorite number is 8
My favorite number is 0
My favorite number is 5
My favorite number is 4
My favorite number is 7
My favorite number is 1
Run Code Online (Sandbox Code Playgroud)
正如你自己引用的那样:
执行这些程序的环境是确定性的。
因此Go Playground的设计不允许创建真正的伪随机输出。
这样做是为了缓存结果,以最大限度地减少后续运行的 CPU/内存使用量。因此,引擎可以只评估您的程序一次,并在您或其他任何人再次运行它时提供相同的缓存输出。
出于同样的目的,开始时间被锁定为一个常数。
You may want to read a blog post on how and why it's implemented this way: https://blog.golang.org/playground