如何在Go中生成固定长度的随机数? [英] How to generate a fixed length random number in Go?

查看:536
本文介绍了如何在Go中生成固定长度的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中生成固定长度随机数最快,最简单的方法是什么?

要生成8位长的数字,rand.Intn(100000000)的问题是结果可能远远少于8位,并且用前导零填充它对我来说似乎不是一个好答案.

也就是说,我更关注随机性的质量,即其长度.因此,我在想,对于这个特定的问题,下面的方法是最快,最简单的方法吗?

99999999 - rand.Int63n(90000000)

即,我想Int63n对于我的情况可能比Intn好.是真的,还是只是一厢情愿的想法?关于完整的8位数字的随机性,两者是否相同,或者真的有一个比另一个更好?

最后,还有什么比以上更好的方法了?

更新:

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

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

谢谢

解决方案

这是用于生成范围内数字的通用功能

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

游乐场

上查看

在您的特定情况下,尝试生成8位数字,范围为(10000000, 99999999)

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

解决方案

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)

这篇关于如何在Go中生成固定长度的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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