如何在类中编写有效的正态分布

时间:2015-08-12 05:08:04

标签: c++ boost random normal-distribution

我在相同的情况下运行我的项目(即当然除了随机数)。有时候实验运行顺利,有时则没有。我怀疑随机生成器的实现方式。这是我使用标准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;
  }
}

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

1 个答案:

答案 0 :(得分:2)

Box-Muller(在评论中提到)是一种常见的方法,但与许多替代方案相比,它相对较慢,因为它依赖于超越函数(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,了解用于生成法线的主要技术和头对头比较的相当好的讨论。