每次从分布中抽取样本时,我都希望更改离散分布的权重,而不必每次绘制新的随机样本时都初始化一个对象。
改变权重的原因是,这是我正在实现的粒子滤波算法的一部分。我不想每次实例化一个新对象的原因是,我想要将随机种子一次外部设置到整个程序中,以便获得可重复的结果。
这里也提出了类似的问题,但没有完全回答我的具体问题:
配发后如何改变权重? -建议在每次抽签时初始化
为什么boost的随机数生成(按正态分布)总是给出相同的值? -不改变参数
问题是,目前在一个高级程序中,我每次调用包含随机数生成的函数,就会得到相同的随机数序列。数字应该是不同的。
下面是我想要做的事情的简化示例。
typedef boost::mt19937 RNGType;
RNGType rng;
nParticles = 10;
int main()
{      
  std::vector<int> indices(nParticles);
  int nIterations(5);
  for (int i=0; i<nIterations; ++i)
  {
    // Pseudo code. In the final version the weights will change on each loop
    std::vector<double> weights = { 0.1, 0.4, ..., 0.3 }; // Vector length 10
    indices = filter(weights);
    std::cout << indices << std::endl;
  }
  return 0;
}
std::vector filter(std::vector<double> weights)
{
  std::vector<int> indices(nParticles);
  boost::random::discrete_distribution<int,double> weightdist(weights);
  boost::variate_generator< RNGType, 
      boost::random::discrete_distribution<int,double> >
      weightsampler(rng, weightdist);
  for (int i=0; i<nParticles ; ++i)
  {
    indices[i] = weightsampler();
  }
  return indices;
}这是返回,例如。
1,8,9,2,3,5,1,9,9,9 // Good: each number is "random"
1,8,9,2,3,5,1,9,9,9 // Bad: This is the same as the previous line
1,8,9,2,3,5,1,9,9,9
1,8,9,2,3,5,1,9,9,9
1,8,9,2,3,5,1,9,9,9对于如何为每个过滤器函数输出得到不同的数字,有什么想法吗?
发布于 2014-02-10 16:22:36
您每次都会更改权重,因为每次调用时都会将一组新的权重传递给filter()函数。您的示例为每个调用生成相同的输出是因为罗氏构造函数按值接受两个参数。因此,在每次调用时,您都会创建RNG的副本,原始RNG对象从未看到对副本内部状态的更改。
将变量生成器的模板参数更改为引用类型
boost::variate_generator<RNGType&, boost::random::discrete_distribution<int,double>>
//                             ^^^
//               doesn't copy RNG anymore您还可能希望将filter()函数签名更改为
std::vector filter(std::vector<double> const& weights)这将避免对每个调用的输入参数进行不必要的复制。
现场演示
https://stackoverflow.com/questions/21681907
复制相似问题