8

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.

Thanks in advance.

puccio
  • 3,054
  • 8
  • 29
  • 20
  • A C code snippet is available in a similar, [later question (click here)](http://stackoverflow.com/questions/17995894/normalgaussian-distribution-function-in-c/23609868#23609868) – jcollomosse May 12 '14 at 13:46

4 Answers4

15

The standard library does not. Boost.Random does, however. I'd use that if I were you.

jalf
  • 243,077
  • 51
  • 345
  • 550
13

C++ Technical Report 1 adds support for random number generation. So if you're using a relatively recent compiler (visual c++ 2008 GCC 4.3), chances are that it is available out of the box.

See here for sample usage of std::tr1::normal_distribution (and many more).

  • 1
    If it is not there yet, you can find it as part of Boost, too: http://www.boost.org/doc/libs/1_39_0/doc/html/boost_tr1/subject_list.html#boost_tr1.subject_list.random – stephan Jul 10 '09 at 14:55
6

The GNU Scientific Libraries has this feature. GSL - Gaussian Distribution

Matt Price
  • 43,887
  • 9
  • 38
  • 44
4

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 <iostream>
#include <iomanip>
#include <map>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::normal_distribution<> dist(2, 2);

    std::map<int, int> 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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740