本文介绍了生成随机位 - C rand() 中缺乏随机性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rand() 生成 0 或 1(rand() % 2).我正在使用当前时间 (srand(time(NULL))) 为其播种.

I am using rand() to generate either 0 or 1 (rand() % 2). I am seeding it using the current time (srand(time(NULL))).

经过多次调试后,我意识到 rand() 永远不会连续 16 次或更多次返回偶数(奇数).

After much debugging, I realised that rand() never returns an even (odd) number 16 or more times in a row.

这是一个已知问题吗?C有没有更好的PRNG?

Is this a known issue? Is there a better PRNG that comes with C?

我使用 Visual Studio 2010 在 Windows 7 上运行.

I am running on Windows 7 using Visual Studio 2010.

推荐答案

不要使用 rand()%2,试试 rand()>(RAND_MAX/2)>.你只能假设 rand() 在区间 [0, RAND_MAX] 上是一致的.

Instead of using rand()%2, try rand()>(RAND_MAX/2). You can only assume rand() to be uniform on the interval [0, RAND_MAX].

这是 Shahbaz 在评论中提出的建议,我在发布此答案后才注意到.

This was suggested by Shahbaz in the comments, which I only noticed after I posted this answer.

ArjunShankar 在我之前的措辞中叫我:rand() 仅在区间 [0, RAND_MAX] 上指定为统一的"

ArjunShankar called me out on my previous wording: "rand() is only specified to be uniform on the interval [0, RAND_MAX]"

来自 C99 标准:

rand 函数计算范围为 0 到RAND_MAX.

从技术上讲,未指定均匀性(或等分布),但它是用于实现常用 PRNG(例如 Mersenne Twister)的事实上的标准.这是为了允许程序员轻松创建具有非均匀分布的自定义 PRNG.如果没有此属性,程序员将被迫从头开始实现自定义 PRNG.

Technically, uniformity (or equidistributed) is not specified, but is the de-facto standard used for implementations of commonly used PRNG's (e.g. Mersenne Twister). This is to allow a programmer to easily create a custom PRNG with a non-uniform distribution. Without this property, a programmer is forced to implement a custom PRNG from scratch.

这篇关于生成随机位 - C rand() 中缺乏随机性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 18:43
查看更多