Random bit generation - no randomness in C rand ()

I use rand() to generate 0 or 1 ( rand() % 2 ). I sow it using the current time ( srand(time(NULL)) ).

After much debugging, I realized 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 Windows 7 using Visual Studio 2010.

+8
source share
4 answers

Instead of rand()%2 try rand()>(RAND_MAX/2) . You can assume that rand() is uniform on the interval [0, RAND_MAX] .

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

Edit: ArjunShankar called me according to my previous wording: "rand () is set only as a single on the interval [0, RAND_MAX]"

From the C99 standard:

The rand function computes a sequence of pseudo-random integers ranging from 0 to RAND_MAX.

Technically, uniformity (or equidistributed) is not specified, but is the de facto standard used for implementations of the commonly used PRNG (e.g., Mersenne Twister). This allows the programmer to easily create their own PRNG with uneven distribution. Without this property, the programmer is forced to implement his own PRNG from scratch.

+12
source

I would suggest using the best RNG. You are working on Windows to use rand_s : this is a Microsoft extension using Windows cryptographic RNG.

+2
source

rand() good to suck. random() slightly better (sometimes), but drand48() and his family are much better.

In this you are better off, look at mersen twister or other PRNG libraries. Or check / dev / random if this can provide enough data for your needs.

+1
source

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

0
source

All Articles