I must generate a random number using boost libraries, I use this code:
boost::mt19937 gen;
boost::uniform_int<> dist(kUIMinManPort, kUIMaxManPort);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> >
var(gen, dist);
unsigned int value = (unsigned int)var();
return boost::lexical_cast<std::string>(value);
Obviously I import all necessary libraries. Well the code compiles but the problem is that I obtain the same numbers....
OK OK... do not worry, I am not such a newbie when talking about casual (or better pseudo-casual) number generation. I know that we must provide a seed and that, depending on this seed, a sequence of pseudocasual numbers will be provided.
So my code becomes this:
boost::mt19937 gen(static_cast<unsigned int>(std::time(0)));
boost::uniform_int<> dist(kUIMinManPort, kUIMaxManPort);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> >
var(gen, dist);
unsigned int value = (unsigned int)var();
return boost::lexical_cast<std::string>(value);
Well, the problem is that we get almost the same number everytime I call this function (inside a for cycle). I suspect that the time depending seed provided to the generation core of the boost random library does not vary during the period of time of a for cycle, that's why get almost the same number everytime I run a cycle and get a random number... The question is: how to solve this problem in an efficient way??? I suppose a best practice is given... Well, I'm not the only one having such a problem :)
Thanks...
time(0) + (long long)getpid() << 32
on unix. There is an equivalent on windows. – Alexandre C.boost::random_device
(akastd::random_device
in C++0x) is a nicer source of seeds thanstd::time()
. But it still shouldn't be called on every iteration of a loop. – Cubbi