M
Markus Dehmann
According to several C++ tutorials, calling srand like this to
initialize the random number generator seems to be standard:
srand((unsigned)time(0));
But it leads to the same random number sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds? And integrating the process ID or
current amount of free memory or whatever? Is there a C++ library that
does it right?
Here is the program that outputs 3 different random numbers on a
../a.out call, but two identical sequences if called in a row like:
../a.out; ./a.out
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand((unsigned)time(0));
for(unsigned i=0; i<3; ++i){
cout << rand() << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
Thanks!
Markus
initialize the random number generator seems to be standard:
srand((unsigned)time(0));
But it leads to the same random number sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds? And integrating the process ID or
current amount of free memory or whatever? Is there a C++ library that
does it right?
Here is the program that outputs 3 different random numbers on a
../a.out call, but two identical sequences if called in a row like:
../a.out; ./a.out
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand((unsigned)time(0));
for(unsigned i=0; i<3; ++i){
cout << rand() << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
Thanks!
Markus