OiO.lk Blog C# First call to rand after calling srand doesn't look random at all
C#

First call to rand after calling srand doesn't look random at all


I’m getting strange behavior out of the rand() function in C. The result of the first call to rand() after srand() looks very predictable and un-random. I tried both with the seed from 0 to 10, and using the system time as a seed and sleeping 1 sec after each call to srand, produced similar results: the output is almost a linear function of the seed.

EDIT: I changed my test program so that the first call to rand after calling srand, determines how many times rand is called to generate the result. Following is first the original program with seed 0-10 and its output; then, the modified program with seed 0-10 and its output.

#include <string.h>
#include <windows.h>
#include <tchar.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
  unsigned int randnum, ind;
  char line[130]; 

  for (ind=0; ind <=10; ind++) {
    srand(ind);
    randnum = rand();
    printf("%u, %u, %u, \n", ind, randnum, rand());
  }

  gets(line);
  return 0;
}

Output:

0, 38, 7719,
1, 41, 18467,
2, 45, 29216,
3, 48, 7196,
4, 51, 17945,
5, 54, 28693,
6, 58, 6673,
7, 61, 17422,
8, 64, 28170,
9, 68, 6151,
10, 71, 16899,

The result increases by 3 or 4 when the seed is incremented by 1.
Now, the modified program and its results:

#include <string.h>
#include <windows.h>
#include <tchar.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
unsigned int randnum, nreps, ind1, ind2;
char line[130], ok; 

for (ind1=0; ind1 <=25; ind1++) {
    srand(ind1);
    nreps = rand() % 11;
    for (ind2=1; ind2 <= nreps; ind2++) rand ();
    randnum = rand();
    printf("%u, %u, %u \n", ind1, nreps, randnum);
}
gets(line);
return;
}

Output:

0, 5, 8365
1, 8, 24464
2, 1, 24198
3, 4, 23577
4, 7, 10960
5, 10, 28321
6, 3, 5206
7, 6, 11794
8, 9, 4670
9, 2, 22398
10, 5, 6722
11, 8, 28519
12, 0, 5628
13, 4, 30076
14, 7, 12236
15, 10, 28761
16, 2, 27002
17, 6, 15290
18, 9, 3191
19, 1, 209
20, 4, 24795
21, 8, 32575
22, 0, 14808
23, 3, 16714
24, 6, 27567
25, 10, 29202

That looks much better!



You need to sign in to view this answers

Exit mobile version