OK, so I've learned through Google search that MinGW does not handle random number generation very well. Even when using a random generator seed based upon the time, it creates the same random numbers each time the program is run. This happens whether we used the old style rand, or the new style mst. The bottom line is that randomization does not really work in MinGW. An example of -- you get what you pay for. Since MinGW is free I really cannot complain about this too much.
But, my first question is -- has a recent update for MinGW fixed this, or is one planned for the future?
The solution that was suggested in my Google search was to use the randomization functions in Boost. As a result, I created the following funtion:
typedef boost::minstd_rand gen_type;
vector <int> RandomInts (unsigned items, int low, int high)
{
sleep(1); // sleep to update time so that random seed is different each time
vector <int> out;
gen_type RNG(time(nullptr)); // random seed
boost::uniform_int<> distro(low, high);
boost::variate_generator <gen_type&, boost::uniform_int<> > randnum(RNG, distro);
for (unsigned i=0; i<items; i++) out.push_back(randnum());
return out;
}
Although this function seems to work, as far as my needs are concerned, I wonder if I am doing this the best way possible.
There are three issues I wonder about:
-
I use a sleep function to advance the time one second before the randomization takes place. I found that if I do not do this, the random seed based upon time can be the same on multiple iterations of the function (less than one second between each function call). So, my solution makes sure that the random seed is different each "time." But, it also adds one second to the program execution. Is there a better way to accomplish this goal without sacrificing run time?
-
I call the random seed generator in the funciton, which means that it gets seeded each time I call the function. Advice I've read says to only seed the randomization once. However, if I put the seed generator outside the program I get the same set of random numbers each time the function is called within a single program run. So, it would seem that re-seeding is actually needed. If this is not correct, what else should I do?
- I originally wanted this function to return a single int, rather than a vector of ints. Several problems occurred. First, the one second delay in the program would cause the generation of 10 random ints to take at least 10 seconds -- that's way too long. Second, the function would always seem to return the same int -- so if I called it 10 times in a row I would get 10 identical numbers. Although the choice of numbers was random, the repitition of that number was not. Can I solve this problem while also solving the time problem?
Thanks for your help.