I don’t understand why srand() generates so similar random numbers between runs!
I am trying to run the following code
srand ( time(NULL) );
int x = rand();
cout << x << endl;
However instead of a proper random number I always end up with almost the same number, which is growing slowly as the time goes. So I get numbers like: 11669, 11685, 11701, 11714, 11731.
What am I doing wrong?
I am using Visual Studio 2010 SP1.
OK, is srand() really that simple? I mean how would anyone call it a random function?
srand(1) => rand() = 41
srand(2) => rand() = 45
srand(3) => rand() = 48
srand(4) => rand() = 51
....
First,
srand()isn’t a random function; it sets up the starting pointof a pseudo-random sequence. And somewhat surprisingly, your
implementation of
rand()seems to be returning a value based on theprevious state, and not on the newly calculated state, so that the first
value after a call to
srand()depends very much on the value passed tosrand(). If you were to write:, I’m sure you’ll see a lot more difference.
FWIW: I tried the following on both Windows and Linux:
Invoked 10 times at a one second interval, I got:
with VC++ under Windows—you’ll note the very low variance of the
first call to
rand()—andwith g++ under Windows; in this case, even the first value read is
relatively random.
If you need a good random generator, you’ll probably have to use one
from Boost; the standard doesn’t say much about what algorithm should be
used, and implementations have varied enormously in quality.