Margsalia Polar Method

This is very similar to use the Box-Muller Transform except it uses cartesian coordinates instead of polar coordinates.

This is faster because we don’t use and . A non-thread safe implementation in C++ using the mean and standard deviation:

double generateGaussian(double mean, double stdDev) {
    static double spare;
    static bool hasSpare = false;
 
    if (hasSpare) {
        hasSpare = false;
        return spare * stdDev + mean;
    } else {
        double u, v, s;
        do {
            u = (rand() / ((double)RAND_MAX)) * 2.0 - 1.0;
            v = (rand() / ((double)RAND_MAX)) * 2.0 - 1.0;
            s = u * u + v * v;
        } while (s >= 1.0 || s == 0.0);
        s = sqrt(-2.0 * log(s) / s);
        spare = v * s;
        hasSpare = true;
        return mean + stdDev * u * s;
    }
}

C++11 GNU GCC libstdc++‘s implementation of std::normal_distribution uses the Marsaglia polar method, as quoted from herein.