c++ - 如何在类中编写高效的正态分布

标签 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;
  }
}

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

最佳答案

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 .

如果速度是主要问题,Ziggurat algorithm Marsaglia 和 Tsang 是最快的之一,并且根据统计测试判断具有出色的质量。请看this paper对用于生成法线的主要技术进行了很好的讨论,并进行了直接比较。

关于c++ - 如何在类中编写高效的正态分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31956475/

相关文章:

c++ - ZMQ PUSH PULL 每条消息发送一半

c++ - 在 SWIG 中将结构从 C++ 函数返回到 Python

c++ - BGL 中的 slistS 发生了什么?

c++ - 'make_shared' 不明确

c++ - 多组独立的随机数

c - 在带链表的递归函数中使用 rand()

c++ - 如何使用 Windows API 在 C++ 中播放声音?

c++ - (c++) 在类中声明类成员

c++ - CMake 使用绝对路径导出目标

sql - 从 SQL Server 获取随机数据但没有重复值