Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious random number - wanting to be the same even after "srand()" [duplicate]

Tags:

c++

random

Possible Duplicate:
Rand generating same numbers

The following is tried when answering another question on StackOverflow:

#include <time.h>
#include <iostream>

using namespace std;

main() {
  srand ( time(NULL) );
  cout << (float) rand() / RAND_MAX << endl;
  cout << ((float) rand())  << endl;
  cout << RAND_MAX << endl;
  cout << (float) rand() / RAND_MAX << endl;
}

Very strangely, the first output number is always a similar number, either on Windows 7 with cygwin or on Mac with Leopard.

The last number is a good random number from 0 to 1. If the first cout line is commented out, the first printed random number is always a similar value one.

How could that be happening?

like image 325
nonopolarity Avatar asked Dec 01 '22 04:12

nonopolarity


1 Answers

I have stumbled upon this phenomenon myself in the past. The first call to rand() in four sequential runs of a test program gave the following output:

27592
27595
27598
27602

Notice how similar those numbers are? This is because the random number generator is initialized with the current time, and the first result is heavily influenced by that. Similar initial values for srand yield similar initial results for rand. It's as simple as that.

This similarity is irrelevant if you calculate rand() % n, but if you go with the rand() / m approach, this is a problem. For example, if you divide rand() by 100, you will get the same number 3 times in a row! Now let's take a look at the second result of rand() in four sequential runs:

11520
22268
248
10997

This looks much better, doesn't it? A simple quick-fix is to call rand() a few times after seeding and simply ignoring the result.

int main()
{
    srand(time(0));
    rand(); rand(); rand();

    std::cout << rand() / float(RAND_MAX) << std::endl;
}
like image 65
fredoverflow Avatar answered Dec 21 '22 10:12

fredoverflow