简体   繁体   中英

C++ Boost random numeric generation problem

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...

static boost::mt19937 gen(static_cast<unsigned int>(std::time(0)));

The static makes sure that the generator is only created once. The problem is that time isn't changing fast enough. If you call your function in the same millisecond, you'll get the exact same results. Unfortunately, your code is just that fast that you're calling it in the same millisecond.

Making the generator static (or a singleton pattern, or a global variable...) will solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM