C++ TR1: how to use the normal_distribution?

后端 未结 4 1676
野的像风
野的像风 2020-12-11 03:42

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

相关标签:
4条回答
  • 2020-12-11 03:57

    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)

    0 讨论(0)
  • 2020-12-11 04:01

    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();
    
    0 讨论(0)
  • 2020-12-11 04:04

    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); 
     }
    
    0 讨论(0)
  • 2020-12-11 04:11

    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.

    0 讨论(0)
提交回复
热议问题