duanqiang3925 2018-03-15 08:10
浏览 24
已采纳

带时间包的随机数

So I'm looking to generate a random number in Go, and the recommended way of doing this is apparently to use something like this:

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

func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

But this seems like a solution where the random number isn't random if two people run this script at the same time. The seed is apparently the time of execution, and this could very well be the same in some cases.

Isn't this a pretty inaccurate way of generating a random number? I ran it a couple times, and it just gives me the same number if I run it fast enough. Isn't there a better solution for a random number? Like, for example, using cryptography or something as the seed? Time just doesn't seem like the best seed.

  • 写回答

1条回答 默认 最新

  • dqphg40600 2018-03-15 08:22
    关注

    math/rand isn't meant for anything secure. For secure randomness, use crypto/rand.

    If you simply want to get rid of the 1-second granularity, use time.Now().UnixNano() instead of time.Now().Unix(). You can also mix in data that's likely to vary between systems, like os.Getpid() or a hardware address from net.Interfaces(), to prevent different systems "accidentally" generating the same value at the same time (again, this is not a security measure).

    For something in between, read 64 bits from the Reader in crypto/rand, and use that to seed math/rand :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line