Lack of randomness in C rand()

2019-01-15 15:35发布

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

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

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

I am running on Windows 7 using Visual Studio 2010.

标签: c random
4条回答
Lonely孤独者°
2楼-- · 2019-01-15 16:01

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

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

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

From the C99 standard:

The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-15 16:02

rand() is well-known to suck. random() is a bit better (sometimes), but drand48() and its family are much better.

In you need better than that, look into the mersene twister or other PRNG libraries. Or check out /dev/random if that can provide enough data for your needs.

查看更多
男人必须洒脱
4楼-- · 2019-01-15 16:05

I'd suggest using a better RNG. You're running on Windows so you can use rand_s: It's a Microsoft extension that uses the Windows cryptographic RNG.

查看更多
等我变得足够好
5楼-- · 2019-01-15 16:10

Well, You can use Algorithms for Mersenne Twister or WELL. The code for WELL is on here(I don't have enough reputations) http://i.stack.imgur.com/q6VPL.pngenter image description here

查看更多
登录 后发表回答