简体   繁体   English

困难 Go 兰特 package

[英]Difficulty with Go Rand package

Is there any Go function which returns true pseudo random number in every run?是否有任何 Go function 在每次运行中返回真正的伪随机数? What I actually mean is, consider following code,我的意思是,考虑下面的代码,

package main

import (
    "fmt"
    "rand"
)

func main() {
    fmt.Println(rand.Int31n(100))
}

Every time I execute this code, I get the same output. Is there a method that will return different, random results each time that it is called?每次执行此代码时,我都会得到相同的 output。是否有一种方法每次调用时都会返回不同的随机结果?

The package rand can be used to generate pseudo random numbers, which are generated based on a specific initial value (called "seed"). rand可用于生成伪随机数,其基于特定初始值(称为“种子”)生成。

A popular choice for this initial seed is for example the current time in nanoseconds - a value which will probably differ when you execute your program multiple times. 这个初始种子的流行选择是例如以纳秒为单位的当前时间 - 当您多次执行程序时,该值可能会有所不同。 You can initialize the random generator with the current time with something like this: 您可以使用当前时间初始化随机生成器,如下所示:

rand.Seed(time.Now().UnixNano())

(don't forget to import the time package for that) (别忘了导入时间包)

There is also another package called crypto/rand which can be used to generate better random values (this generator might also take the user's mouse movements, the current heat of the processor and a lot of other factors into account). 还有另一个名为crypto / rand的软件包可以用来生成更好的随机值(这个生成器也可以考虑用户的鼠标移动,处理器的当前热量以及许多其他因素)。 However, the functions in this package are several times slower and, unless you don't write a pass-phrase generator (or other security related stuff), the normal rand package is probably fine. 但是,这个包中的函数要慢几倍,除非你没有写一个密码生成器(或其他安全相关的东西),普通的rand包可能没问题。

You have to seed the RNG first. 你必须首先播种RNG。

I've never used Go, but it's probably rand.Seed(x); 我从来没用过Go,但它可能是rand.Seed(x);

rand.Seed(time.Now().UnixNano()) works on Ubuntu. rand.Seed(time.Now().UnixNano())适用于Ubuntu。 I spent forever researching rand.Seed(time.Nanoseconds()) . 我花了很多时间研究rand.Seed(time.Nanoseconds()) I finally found the Example: Google Search 2.1 on the golang tour. 我终于在golang之旅中找到了例子:Google Search 2.1。

To sum up the answers above, you can write your own random number generator with rand.Seed(n) .总结以上答案,您可以使用rand.Seed(n)编写您自己的随机数生成器。 n must be a different number each time you seed.每次播种时 n 必须是不同的数字。 Here is an example:这是一个例子:

func RandomInt(n int) int {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(n)
}

func RandomIntFromRange(min int, max int) int {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(max - min + 1) + min
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM