Mick Mick - 1 month ago 13
C++ Question

How to use std::normal_distribution

I am an experienced C programmer that is occasionally forced to use a little bit of C++.

I need to generate random numbers from a normal distribution with a variety of means and variances. If I had a C function that did this called

normal(float mean, float var)
then I could write the following code:

int i;
float sample;
for(i = 0;i < 1000;i++)
{
sample = normal(mean[i],variance[i]);
do_something_with_this_value(sample);
}


Note that there is a different mean and variance for each value of i.

C does not contain a function called normal, but C++ does, well actually its called std::normal_distribution. Unfortunately my C++ is not good enough to understand the syntax in the documentation. Can anyone tell me how to achieve the functionality of my C code but using std::normal_distribution.

Answer

std::normal_distribution isn't function but templated class

you can use it like this:

#include <random>

int main(int, char**)
{
    // random device class instance, source of 'true' randomness for initializing random seed
    std::random_device rd; 

    // Mersenne twister PRNG, initialized with seed from previous random device instance
    std::mt19937 gen(rd()); 

    int i;
    float sample;
    for(i = 0; i < 1000; ++i)
    {
        // instance of class std::normal_distribution with specific mean and stddev
        std::normal_distribution<float> d(mean[i], variance[i]); 

        // get random number with normal distribution using gen as random source
        sample = d(gen); 

        // profit
        do_something_with_this_value(sample); 
    }
    return 0;
}