A way change the seed of boost::random in every di

2019-08-07 14:41发布

问题:

I use boost::random to generate a random variable that follows uniform distribution.

boost::mt19937 gen(2014/*time(NULL)*/);
boost::uniform_real<> dist(0, 1);
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(gen, dist);  

With this variable,I uniformly choose a different starting graph node in every different experiment.

for(unsigned int i=0; i < numQueries; i++)
{
    //source node id
    sourceID = (unsigned int) ( 1 + random() * G.getNumNodes());
    //...
}

But I'm in need of a way to initialize the seed differently in each different run of my program, as I get the same sequence of starting nodes in every different run now.

回答1:

You can use boost::random_device to use the machine's random pool (which is non-deterministic) to seed your deterministic generator.

#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <iostream>

unsigned int numQueries = 10;

int main(int argc, char* argv[])
{
   boost::random_device dev;
   boost::mt19937 gen(dev);
   //boost::mt19937 gen(2014/*time(NULL)*/);
   boost::uniform_real<> dist(0, 1);
   boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(gen, dist); 

   for(unsigned int i=0; i < numQueries; i++)
   {
       // I don't have G, so I'm just going to print out the double
       //sourceID = (unsigned int) ( 1 + random() * G.getNumNodes());
       double sourceID = (random());
       std::cout << sourceID << std::endl;
   }

   return 0;
}


标签: c++ boost