NO

Author Topic: rand() not very random at all  (Read 2541 times)

WesL

  • Guest
rand() not very random at all
« on: November 19, 2016, 04:11:11 PM »
I understand that a compiler's builtin rand() function is usually a simple/fast implementation of a random number generator, but the Pelles 8 rand() function has some issues that make it unusable for even basic usage.

When the seed is even, rand() returns alternating odd and even values.  When the seed is odd, rand() starts off with a sequence of consecutive odds.  I've observed this to be as many as 16 consecutive odds.  I discovered this issue when simulating rolling pairs of dice and after rolling millions of pairs of dice, they ALL came out odd.

The following tiny program illustrates the problem.

Code: [Select]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
int i, r;
unsigned seed;

seed = (unsigned)time(NULL);
// seed = 0;  // alternating odd/even
// seed = 1;  // starts with a string of 16 odds, then 9 evens
srand(seed);

printf("RAND_MAX = %d, seed = %u\n\n",RAND_MAX, seed);
for (i=0; i<100; i++)
{
r = rand();
printf("%10d\n",r);
}

return 0;
}

Edit: slightly modified the code
« Last Edit: November 19, 2016, 07:35:34 PM by WesL »