2016-03-15 02:27
浏览 295


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?


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


图片转代码服务由CSDN问答提供 功能建议


说要生成8位长的数字, rand.Intn(100000000)的问题是结果可能远远少于8位数字,并且

也就是说,我更关心随机性的质量,从长度的角度来看。 所以我在想,对于这个特定的问题,下面的方法是最快,最简单的方法吗?


也就是说,我猜 Int63n 对于我来说,可能比 Intn 更好。 是真的,还是只是一厢情愿? 关于完整的8位数字的随机性,两者是否相同,或者确实有一个比另一个更好?



请不要提供 low + rand(hi-low) 作为答案,众所周知。 这等效于我现在正在做的事情,并且没有回答我的真实问题,“关于全8位数的随机性,两者是否相同,或者确实有一个比另一个更好 ?“

如果没人能回答,我将在两者之间绘制一个二维散点图,然后找出自己... \ n


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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 Playground

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

    打赏 评论
  • douxiajiao8445 2016-03-15 02:38

    It depend on value range you want to use.

    1. If you allow value range [0-99999999] and padding zero ip number of char < 8, then use fmt like fmt.Sprintf("%08d",rand.Intn(100000000)).

    2. If you dont want padding, which value in range [10000000, 99999999], then give it a base like ranNumber := 10000000 + rand.Intn(90000000)`

    打赏 评论

相关推荐 更多相似问题