C++ TR1: how to use the normal_distribution?

puccio picture puccio · Jul 13, 2009 · Viewed 10k times · Source

I'm trying to use the C++ STD TechnicalReport1 extensions to generate numbers following a normal distribution, but this code (adapted from this article):

mt19937 eng;
eng.seed(SEED);

normal_distribution<double> dist;
// XXX if I use the one below it exits the for loop
// uniform_int<int> dist(1, 52);

for (unsigned int i = 0; i < 1000; ++i) {
  cout << "Generating " << i << "-th value" << endl;
  cout << dist(eng) << endl;
}

only prints 1 "Generating..." log message, then never exits the for loop! If I use the distribution I commented out instead, it terminates, so I'm wondering what I'm doing wrong. Any idea?

Thanks a lot!

Answer

pmeerw picture pmeerw · Nov 24, 2010

I have had the same issue with the code originally posted and investigated the GNU implementation of

first some observations: with g++-4.4 and using the code hangs, with g++-4.5 and using -std=c++0x (i.e. not TR1 but the real thing) above code works

IMHO, there was a change between TR1 and c++0x with regard to adaptors between random number generation and consumption of random numbers -- mt19937 produces integers, normal_distribution consumes doubles

the c++0x uses adaption automatically, the g++ TR1 code does not

in order to get your code working with g++-4.4 and TR1, do the following

std::tr1::mt19937 prng(seed);
std::tr1::normal_distribution<double> normal;
std::tr1::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);
double r = randn();