Search code examples
c++xcoderandommacos-sierranormal-distribution

Build a C++ normal distributed random number generator on Xcode 8.3


I'm trying to build a function that returns a positive random number taken from a N(0,1) distribution.

I've looked around on the Internet and I tried to use two different methods.

This is the first one, in which I try to set the random seed from the system clock. I found it on this page of Cplusplus.com: std::normal_distribution::(constructor)

unsigned long normal01_rand() {

        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

        std::default_random_engine generator (seed); 

        std::normal_distribution<unsigned long> distribution (0.0, 1.0); 

        long random_value = distribution(generator);
        if (random_value < 0) {
            random_value = random_value * (-1);
        }
        return random_value;
}

And this is the second one. I didn't really understand how this works in detail but I found it as an answer to a similar question and I thought to give it a try:

unsigned long normal01_rand() {

        std::random_device rd;

        std::mt19937 e2(rd());

        std::normal_distribution<unsigned long> distribution (0.0, 1.0);

        long random_value = distribution(e2);
        if (random_value < 0) {
            random_value = random_value * (-1);
        }
        return random_value;
}

Unfortunately none of them works for me. If I use the first one my code gets stuck in an infinite loop when I first try to generate a random number in my code. The second one instead throws me this exception: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)

I can't understand what's going on and why.

Hoping to have been clear enough, thank you everybody in advance.


Solution

  • It is defined as

    template< class RealType = double > class normal_distribution
    

    where for RealType you could use only float, double or long double, otherwise it is undefined.

    Code should be

    std::normal_distribution<double> distribution (0.0, 1.0);
    
    double random_value = distribution(e2);
    return fabs(random_value);