Go Rand套餐很难 [英] Difficulty with Go Rand package

查看:170
本文介绍了Go Rand套餐很难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Go函数在每次运行中返回真伪随机数?我的意思是,请考虑以下代码:

  package main 

import(
fmt
rand


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

每次执行此代码时,我都会得到相同的输出。是否有一种方法会在每次调用它时返回不同的随机结果? http://golang.org/pkg/randrel =noreferrer> rand 可用于生成基于特定初始值(称为种子)生成的伪随机数。 p>

这个初始种子的流行选择是例如当前时间(以纳秒为单位) - 当您多次执行程序时可能会有所不同。你可以用当前时间初始化随机生成器,像这样:

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

(不要忘记导入 time 还有另外一个叫做 crypto / rand ,它可以用来产生更好的随机值(这个生成器也可能带用户的鼠标移动,当前的热量的处理器和许多其他因素考虑在内)。但是,这个包中的函数要慢几倍,除非你不写一个pass-phrase生成器(或其他与安全有关的东西),否则正常的rand包可能没有问题。


Is there any Go function which returns true pseudo random number in every run? 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?

解决方案

The package rand can be used to generate pseudo random numbers, which are generated based on a specific initial value (called "seed").

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). 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.

这篇关于Go Rand套餐很难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆