C++: generate gaussian distribution

后端 未结 4 1831
囚心锁ツ
囚心锁ツ 2020-12-06 12:28

I would like to know if in C++ standard libraries there is any gaussian distribution number generator, or if you have any code snippet to pass.

Than

4条回答
  •  半阙折子戏
    2020-12-06 12:53

    The answer to this question changes with C++11 which has the random header which includes std::normal_distribution. Walter Brown's paper N3551, Random Number Generation in C++11 is probably one of the better introductions to this library.

    The following code demonstrates how to use this header (see it live):

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::random_device rd;
    
        std::mt19937 e2(rd());
    
        std::normal_distribution<> dist(2, 2);
    
        std::map hist;
        for (int n = 0; n < 10000; ++n) {
            ++hist[std::floor(dist(e2))];
        }
    
        for (auto p : hist) {
            std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                      << p.first << ' ' << std::string(p.second/200, '*') << '\n';
        }
    }
    

    I provide a more general set of examples to random number generation in C++11 in my answer to C++ random float number generation with an example in Boost and using rand() as well.

提交回复
热议问题