Running the program once every second gives these results:
21339
21346
21350
21354
etc.
I'm using Code::Blocks with the GNU GCC Compiler and think the problem may lie with that. When I tried running the code on codepad.org, it ran as it should have.
rand() is a PRNG. It means pseudorandom number generator.
The thing is, you run your program and then exit it right away. So every time you run it, the seed ( srand(time(NULL)); ) is reset. The seed is using time as you can see.
It should give out a better random generation if you do something like:
1 2 3 4 5 6 7
srand(time(NULL));
while( true )
{
cout << rand() << endl;
sleep(1000); // wait for one second and then loop back
}
That sleep() call it absolutely useless there, it will not influence program output in any way, you will get exactly the same results with or without it.
That sleep() call it absolutely useless there, it will not influence program output in any way, you will get exactly the same results with or without it.
+1
Peter87 wrote:
yelnatz's code will probably give better random numbers compared to running Saeraph's code once every second.
+1
You should do an empty rand() before the real rand() so it gets re-pseudorandomly-seeded, like:
Because each time you call rand(), its seed gets re-randomized, mostly the algorithm is a linear multiplication of the seed, so summing up multiplications and capping the result to RAND_MAX ( as done inside rand() )will give a more random value.
Pseudocode Explaination:
1 2 3 4 5 6 7 8
int main()
{
srand(time(0)); // seed is now, say... (40100*4)+2
rand(); // returns 160402, then seed is, say... (160402*4)+2
rand(); // now this was to return 641610 but if it exceeds RAND_MAX
// it gets modulo'ed to RAND_MAX so the number will lower down a lot,
// looking then random. again seed goes multiplied by 4 and added by 2
}
The "(x*4)+2" is a theorical part, but that should be the "issue".
Another solution is to multiply the result from time(0) like:
srand(time(NULL)*436);
and a single call to rand() should be enough.