一种方法在每个不同的程序运行中更改boost :: random的种子

时间:2013-10-21 16:44:41

标签: c++ boost

我使用boost :: random来生成一个遵循均匀分布的随机变量。

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++)
{
    //source node id
    sourceID = (unsigned int) ( 1 + random() * G.getNumNodes());
    //...
}

但是我需要一种方法来在我的程序的每个不同运行中以不同方式初始化种子,因为我现在在每个不同的运行中获得相同的起始节点序列。

1 个答案:

答案 0 :(得分:1)

您可以使用boost::random_device来使用机器的随机池(非确定性)来为确定性生成器播种。

#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;
}