CroCo
CroCo

Reputation: 5741

How to write an efficient normal distribution inside a class

I'm running my project under same circumstances (i.e. except of course the random numbers). Some times the experiment is running smoothly and sometimes is not. I suspect the way random generator is implemented. This is my solution by using standard 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;
  }

}

I've tried boost as well, generally speaking the response is better than my method with STL and this is the code.

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

My first question is is there any thing wrong with my approaches? If so, what is the most efficient way to implement normal distribution inside a class?

Upvotes: 3

Views: 611

Answers (1)

pjs
pjs

Reputation: 19853

Box-Muller (mentioned in the comments) is a common approach, but it's relatively slow compared to many of the alternatives because of its reliance on transcendental functions (log, sin, and cos). It also has a 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.

If speed is a major concern, the Ziggurat algorithm of Marsaglia and Tsang is one of the fastest and has excellent quality as judged by statistical tests. Please see this paper for a pretty good discussion of the major techniques used to generate normals, and head-to-head comparisons.

Upvotes: 2

Related Questions