views:

522

answers:

3

Hi,

I'm trying to use the C++ STD TechnicalReport1 extensions to generate numbers following a normal distributions, 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, the it never exists the for loop! If I change the distribution (ie. with the commented uniform distribution), it terminated, so I'm worndering what I'm doing wrong.. Any idea?

Thanks a lot

A: 

While this appears to be a bug, a quick confirmation would be to pass the default 0.0, 1.0 parameters. normal_distribution<double>::normal_distribution() should equal normal_distribution<double>::normal_distribution(0.0, 1.0)

MSalters
it does not work either, it still remains stuck performing the first computation..
puccio
+1  A: 

This definitely would not hang the program. But, not sure if it really meets your needs.

 #include <random>
 #include <iostream>

 using namespace std;

 typedef std::tr1::ranlux64_base_01 Myeng; 

 typedef std::tr1::normal_distribution<double> Mydist; 

 int main() 
 { 
      Myeng eng; 
      eng.seed(1000);
      Mydist dist(1,10); 

      dist.reset(); // discard any cached values 
      for (int i = 0; i < 10; i++)
      {
           std::cout << "a random value == " << (int)dist(eng) << std::endl; 
      }

 return (0); 
 }
Jagannath
thanks man, it works like a charm, but I'm wondering why with this engine it works, and not with the other..
puccio
Obviously the only difference is your using themt19937 number generator whereas Jagannath uses the std::tr1::ranlux64_base_01.Logically, I guess the bug may be in your implementation of the mt19937 object ( algo which I had never heard about before you did, thx for this :-) ) that is not part of std library.
Stephane Rolland
+1  A: 

If your TR1 random number generation implementation is buggy, you can avoid TR1 by writing your own normal generator as follows.

Generate two uniform (0, 1) random samples u and v using any random generator you trust. Then let r = sqrt( -2 log(u) ) and return x = r sin(2 pi v). (This is called the Box-Mueller method.)

If you need normal samples samples with mean mu and standard deviation sigma, return sigma*x + mu instead of just x.

John D. Cook