在golang中的随机数问题

huangapple go评论75阅读模式
英文:

Random number issue in golang

问题

这是我正在使用的代码:

package main
import "fmt"
import "math/rand"

func main() {
    code := rand.Intn(900000)
    fmt.Println(code)
}

它总是返回 698081。我不明白,问题是什么?

这是代码的链接

编辑

我尝试了 rand.Seed

package main

import "fmt"
import "time"
import "math/rand"

func main() {
    rand.Seed(time.Now().UnixNano())
    code := rand.Intn(900000)
    fmt.Println(code)
}

没有变化。现在它总是返回 452000

这是代码的链接

这是代码的链接

英文:

This is the code I'm working with:

package main
import "fmt"
import "math/rand"

func main() {
	code := rand.Intn(900000)
	fmt.Println(code)
}

It always returns 698081. I don't understand, what the is problem?

> https://play.golang.org/p/XisNbqCZls

Edit:

I tried rand.Seed

package main

import "fmt"
import "time"
import "math/rand"

func main() {
	rand.Seed(time.Now().UnixNano())
	code := rand.Intn(900000)
	fmt.Println(code)
}

There is no change. Now it always returns 452000

> https://play.golang.org/p/E_Wfm5tOdH
>
> https://play.golang.org/p/aVWIN1Eb84

答案1

得分: 24

以下是要翻译的内容:

有几个原因会导致你在 playground 中看到相同的结果:

  1. Golang playground 会缓存结果。
  2. Playground 中的时间始终从相同的时间开始,以使 playground 具有确定性。

最后,rand 包的默认种子是 1,这将使结果具有确定性。如果你使用 rand.Seed(time.Now().UnixNano()),每次执行时都会得到不同的结果。请注意,由于上述第二个原因,这在 playground 上不起作用。

英文:

A couple of reasons why you'll see the same result in the playground

  1. Golang playground will cache the results
  2. The time in the playground always starts at the same time to make the playground deterministic.

Last but not least, the rand package default seed is 1 which will make the result deterministic. If you place a rand.Seed(time.Now().UnixNano()) you'll receive different results at each execution. Note that this won't work on the playground for the second reason above.

huangapple
  • 本文由 发表于 2017年7月30日 06:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/45394684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定