生成随机数

发布于 2024-11-11 14:29:07 字数 256 浏览 4 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱已欠费 2024-11-18 14:29:07

您似乎误解了随机性的本质。这种分布中会出现少量的情况,只是不常见。如果您的模数是 1e6,那么您预计每 500 次左右的调用中只会看到一次低于 2000 的数字。

int main(void) {
    int n=0, r;
    do { r = rand()%1000000; ++n; } while(r>2000);
    printf("it took %d calls\n", n);
    return 0;
}

果然:

$ ./t
it took 462 calls

现在,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.

int main(void) {
    int n=0, r;
    do { r = rand()%1000000; ++n; } while(r>2000);
    printf("it took %d calls\n", n);
    return 0;
}

And sure enough:

$ ./t
it took 462 calls

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.

贩梦商人 2024-11-18 14:29:07

如果您需要这样的随机性,即 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))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文