Reputation: 3156
This is related to this question - random number generation in C++ ... first number not very random
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
return 0;
}
If you run the binary (.exe) over and over again, you will notice that the first result always has the same first three numbers. E.g. 0.54xxxxx always for every run.
No, this isn't because I am spotting patterns where there aren't any. And waiting a few seconds between each run does not help either.
Edit: Only the 1st result has the first same three numbers. The rest are "random looking". Also, the generator is seeded with srand() (on the very first line of the code sample above).
Upvotes: 2
Views: 1980
Reputation: 153939
The randomness of rand
isn't specified by the standard. Most
generators will use the seed to initialize a static variable,
and calculate the next value from that, in a way that should
"appear" random (but is, of course, perfectly deterministic).
My guess is that the implementation on your machine returns the
old value of the static variable, which is equal to the seed the
first time through. (This sort of surprises me, it's usual to
return the new value of the static.)
Anyway, it's a question of the quality of the implementation. (I see the same thing with VC++11, but not with g++.)
EDIT:
Just a quick test to see how varying the seed affects the first number returned:
for ( int i = 1; i <= 10; ++ i ) {
std::srand( i );
std::cout << i << ": " << std::rand() << std::endl;
}
The output with VC++11:
1: 41
2: 45
3: 48
4: 51
5: 54
6: 58
7: 61
8: 64
9: 68
10: 71
With g++ 4.7.2 (CygWin version):
1: 1481765933
2: 816048218
3: 150330503
4: 1632096437
5: 966378722
6: 300661007
7: 1782426941
8: 1116709226
9: 450991511
10: 1932757444
You say that you are seeing this with g++ under Code Blocks: I can only guess that Code Blocks sets things up so that g++ uses the Microsoft libraries, rather that the GNU ones (generally a better solution).
Anyway, the solution is simple: replace the single line you now use to seed the generator with:
std::srand( std::time( NULL ) );
std::rand(); // throw out first value...
And if you need relatively good random numbers, drop std::rand
completely in favor of some of the more rigorously defined
generators in C++11. (You can get them from Boost if you're not
using C++11.)
Upvotes: 6