【问题标题】:How to write an efficient normal distribution inside a class如何在类中编写有效的正态分布
【发布时间】:2015-11-04 13:07:10
【问题描述】:

我在相同的情况下运行我的项目(即当然除了随机数)。有时实验运行顺利,有时则不然。我怀疑随机生成器的实现方式。这是我使用标准 STL 的解决方案

#include <random>
#include <iostream>

class Foo
{
public:
    Foo(){
      generator.seed(seeder);
    }

    double Normalized_Gaussain_Noise_Generator(){
       return distribution(generator);
    }

private:
    std::random_device seeder;
    std::default_random_engine generator;
    std::normal_distribution<double> distribution;
};

int main()
{
  Foo fo;
  for (int i = 0; i < 10; ++i)
  {
    std::cout << fo.Normalized_Gaussain_Noise_Generator() << std::endl;
  }

}

我也尝试过 boost,一般来说响应比我使用 STL 的方法更好,这就是代码。

#include <iostream>
#include <ctime>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

class Foo
{
public:
    Foo() : generator(time(0)), var_nor(generator, boost::normal_distribution<double>() )
    {
    }


    double Normalized_Gaussain_Noise_Generator(){
        return var_nor();
    }

private:
    // Boost Case:
    boost::mt19937 generator;
    boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > var_nor;
};

int main()
{
  Foo fo;
  for (int i = 0; i < 10; ++i)
  {
    std::cout << fo.Normalized_Gaussain_Noise_Generator() << std::endl;
  }
}

我的第一个问题是我的方法有什么问题吗?如果是这样,在类中实现正态分布的最有效方法是什么?

【问题讨论】:

  • 运行不“流畅”是什么意思?
  • @Pradhan,我没有从假设噪声为高斯的随机方法得到预期结果。
  • 好的。只是为了确认一下,您是否打算将高斯噪声设为标准正态?因为这就是你在default construct an std::normal_distribution 时得到的结果。
  • @Pradhan,确实如此。
  • 好的,在这种情况下,我认为差异可以归结为您的std 库的default_random_engine 不如boost::mt19337 作为PRNG。要进行苹果与苹果之间的比较,您能否尝试在第一个示例中使用 std::mt19337 作为生成器,而不是 std::default_random_engine

标签: c++ boost random normal-distribution


【解决方案1】:

Box-Muller(在 cmets 中提到)是一种常用方法,但与许多替代方法相比,它相对较慢,因为它依赖于超越函数(log、sin 和 cos)。它还有一个well-known interaction with linear congruential generators, if those are the underlying source of uniforms, that causes pairs of values to fall on a spiral

如果速度是一个主要问题,Marsaglia 和 Tsang 的 Ziggurat algorithm 是最快的之一,并且根据统计测试判断其质量非常好。请参阅this paper,详细讨论用于生成法线的主要技术以及头对头比较。

【讨论】:

  • 不错的答案!实际上,OPs 问题是因为您在上面指出的 - Box-Muller 在线性同余生成器中表现不佳。 gcc 和 llvm 都使用std::linear_congruential_engine&lt;uint_fast32_t, 16807, 0, 2147483647&gt; 作为std::default_random_engine
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 2016-04-17
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多