0

I have a randomly generated number in a while loop. Since I seed it using time(NULL) when I run it I get a stream of similar results, while I would like it to be more "heterogeneous".

Here's the function:

while(1) {
    srand((unsigned int) time(NULL));   // Seed
    double chance = random() / (double) RAND_MAX;
    if (chance <= 0.95)
        printf("All ok.\n");
    else
        printf("ERROR\n");
}

For example the result of this would look like:

...
All ok.
All ok.
All ok.
All ok.
All ok.
ERROR
ERROR
ERROR
ERROR
ERROR
All ok.
All ok.
All ok.
All ok.
All ok.
...

How can I make the results be more independent from each other?

Robb1
  • 4,587
  • 6
  • 31
  • 60

2 Answers2

3

Don't seed the random in the loop. In general, you only want to seed once:

srand((unsigned int) time(NULL));   // Seed
while(1) {
    double chance = random() / (double) RAND_MAX;
    //...
}

The computer is fast enough to run this loop multiple times within the resolution of the time() function, so you end up reseeding to the same number multiple times.

See https://stackoverflow.com/a/822368/2721883 and https://stackoverflow.com/a/39475626/2721883 for more information on generating random numbers in C.

clcto
  • 9,530
  • 20
  • 42
1

The basic problem is that rand is not generating real random numbers: In computing, to generate random numbers is a very complex problem, and the solution is (generally) to use pseudo-random number, which seem random but each number is built based on the previous one:

e.g.

n0 = 5 (seed = 5)
n1 = ((n0*10+1) % 7) = 2
n2 = ((n1*10+1) % 7) = 0
n3 = ((n2*10+1) % 7) = 1
n4 = ((n3*10+1) % 7) = 4 ...

Where the 10, 7 and 1 have to be carefully selected to get seemingly random numbers.

https://en.wikipedia.org/wiki/Linear_congruential_generator

srand set the first seed value, and each new random use the previously generated random value as seed.

Setting a specific value to srand will generate the exact random numbers serie again and again which is useful for testing. To make something more "random" the seed is usually set to the current time, which is expected to change over time.

The problem in your code is: your loop is too fast in order to get different time values each loop, that mean you set several times the seem value to the seed, generating the same random result.

As suggested, you need to set the seed outside the loop, so each random take the previous random result as seed and generate a seemingly new random number.

srand((unsigned int) time(NULL));   // Seed
while(1) {
    double chance = random() / (double) RAND_MAX;
    if (chance <= 0.95)
        printf("All ok.\n");
    else
        printf("ERROR\n");
}
Adrian Maire
  • 14,354
  • 9
  • 45
  • 85