douwu8251 2016-03-15 02:27
浏览 372
已采纳

如何在Go中生成固定长度的随机数?

What is the fastest and simplest way to generate fixed length random numbers in Go?

Say to generate 8-digits long numbers, the problem with rand.Intn(100000000) is that the result might be far less than 8-digits, and padding it with leading zeros doesn't look like a good answer to me.

I.e., I care about the the quality of the randomness more in the sense of its length. So I'm thinking, for this specific problem, would the following be the fastest and simplest way to do it?

99999999 - rand.Int63n(90000000)

I.e., I guess Int63n might be better for my case than Intn. Is it ture, or it is only a wishful thinking? Regarding randomness of the full 8-digits, would the two be the same, or there is really one better than the other?

Finally, any better way than above?

UPDATE:

Please do not provide low + rand(hi-low) as the answer, as everyone knows that. It is equivalent of what I'm doing now, and it doesn't answer my real question, "Regarding randomness of the full 8-digits, would the two be the same, or there is really one better than the other? "

If nobody can answer that, I'll plot a 2-D scatter plot between the two and find out myself...

Thanks

  • 写回答

2条回答 默认 最新

  • douji6735 2016-03-15 04:59
    关注

    This is a general purpose function for generating numbers within a range

    func rangeIn(low, hi int) int {
        return low + rand.Intn(hi-low)
    }
    

    See it on the <kbd>Playground</kbd>

    In your specific case, trying to generate 8 digit numbers, the range would be (10000000, 99999999)

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog