使用math/rand在golang中生成一个随机变量。

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

Generating a random variable in golang using math/rand

问题

我正在尝试在golang程序中模拟一个硬币翻转。我尝试使用math/rand包,并使用time进行种子初始化。

根据我在其他地方和在线上查找的信息,我的实现应该是正确的:

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

func main() {
	var random int
	var i int
	var j int
	for j != 5 && i != 5 {
		rand.Seed(time.Now().UnixNano())
		random = rand.Intn(2)
		if random == 0 {
			i = i + 1
		}
		if random == 1 {
			j = j + 1
		}
	}
	fmt.Println(i, j)
}

但是,每次运行时,random总是为0。种子也没有改变,这让我感到困惑。由于它在循环内部,难道不应该每次种子初始化时都改变纳秒级的时间吗?

英文:

I'm trying to simulate a coin flip for a program in golang. I'm trying to use math/rand and I'm seeding it using time.

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

From what I've looked up elsewhere on here and online, my implementation should work:

func main() {
    var random int
    var i int
    var j int
    for j != 5 && i != 5 {
	    rand.Seed(time.Now().UnixNano())
	    random = rand.Intn(1)
	    if random == 0 {
		    i = i + 1
	    }
	    if random == 1 {
		    j = j + 1
	    }
    }
fmt.Println(i, j)
}

But, each time I run it, random always end up being 0. The seed doesn't change either, which confuses me. Since it's within the loop, shouldn't the time in nanoseconds change each time it's seeded?

答案1

得分: 5

在循环中不要重新播种,只需在一开始播种一次。

rand.Intn(n) 返回的值大于等于0且小于n。因此,rand.Intn(1)只能返回0,你需要使用rand.Intn(2)来获取0或1。

修正后的代码:
http://play.golang.org/p/3D9osMzRRb

英文:

Don't reseed in the loop, do it only once.

rand.Intn(n) returns a value >= 0 and < n. So rand.Intn(1) can only return 0, you want rand.Intn(2) to get 0 or 1.

Fixed code:
http://play.golang.org/p/3D9osMzRRb

huangapple
  • 本文由 发表于 2015年3月9日 03:38:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/28931015.html
匿名

发表评论

匿名网友

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

确定