dqtiober37522 2011-11-27 20:13
浏览 2
已采纳

Go 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?

  • 写回答

3条回答 默认 最新

  • doushang2023 2011-11-27 20:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ESP32使用MicroPyhon开发,怎么获取485温湿度的值,温湿度计使用的鞋子是Modbus RTU
  • ¥50 苹果MGIE项目部署缺少emb权重
  • ¥15 采用ansys进行机翼在特定路径下的打孔过程中的受力分析
  • ¥15 单片机adb主机连接手机,usb调试密钥无法保存
  • ¥15 已知X和Y有以下关系,求X和Y的关系式
  • ¥15 net core 同时编辑怎么防止数据多保存了
  • ¥15 matlab做ba模型让其在ba和er规则下生长
  • ¥15 请问Quartus的Verilog代码怎么写?
  • ¥100 Mac 版foxmail 收邮件问题
  • ¥15 QWebEngineView