生成随机数
我在 C 中使用 rand() 函数。为了限制范围,我执行 rand() % 1e6,以便数字在 0 到 1e6 之间。生成的一组样本数字如下...
5320428 6386236 5536806 7396572 8798055 1095930 9398652
所以你可以看到数字总是黑白 1e5 和 1e6。但是我想要随机分布的数字,即它们可以是 20、2000 或 2e5 等......,并且不太可能是黑白 1e5 和 1e6。我怎样才能在C中实现这种分布?
I am using rand() function in C. To limit the range I do rand() % 1e6, so that numbers are between 0 and 1e6. A sample set of numbers generated is following...
5320428
6386236
5536806
7396572
8798055
1095930
9398652
So you can see that numbers are always b/w 1e5 and 1e6. However I want numbers which are randomly distributed, that is they can be 20, 2000, or 2e5 etc..., and which are not likely be b/w 1e5 and 1e6. How can I achieve that sort of distribution in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
您似乎误解了随机性的本质。这种分布中会出现少量的情况,只是不常见。如果您的模数是 1e6,那么您预计每 500 次左右的调用中只会看到一次低于 2000 的数字。
果然:
现在,rand 很方便,但它不是一个很好的熵源;生成器通常只是线性同余的(即随机性不是很好并且周期很短)。您可以从 Mersenne Twister 获得更好的随机性。无论哪种情况,您都需要仔细考虑如何为生成器播种 - 系统提供的熵源(例如
/dev/urandom
)通常是最好的。You appear to have misunderstood the nature of randomness. Small numbers will come out of that distribution, just not very often. If your modulus is 1e6, you'd expect to see a number below 2000 only once in every 500 calls or so.
And sure enough:
Now,
rand
is convenient, but it is not a very good source of entropy; the generator is usually only linear congruential (i.e. the randomness is not very good and has a short period). You'd get better randomness from the Mersenne Twister. In either case you need to think carefully about how you're seeding the generator - a system-provided entropy source such as/dev/urandom
is usually best.如果您需要这样的随机性,即 1,2,,..6 位数字将以相同的概率出现,
即您不需要线性,但指数“均匀度”不使用简单的 rand,而是使用:
round(10^(rand(6000000)/1000000))
If you need such randomness that numbers with 1,2,,..6 digits will appear with the same probability,
ie you need not linear, but exponential "evenness" don't use simply rand, but something as:
round(10ˆ(rand(6000000)/1000000))