Implementing Gaussian random variable by using a uniform random variable I'm trying to write a C++ function that will return Gaussian random values, given their means and variances.

There is a library function rand(), which returns random numbers between 0 and RAND_MAX. RAND_MAX does not have a fixed value, but it is guarantied that it will be at least $2^{15}-1$. Its PDF is uniform.

I'm using Central Limit Theorem to transform this rand()into a Gaussian variable. What I'm exactly doing is a to call rand() for a user specified times, then add up their return values, then shift its mean to the user specified mean.


In the plotting above, I called my Gaussian random generator for $10^7$ times, and plotted frequencies of its return values. As you see, its variance is huge, since it is created by sum of a lot of other random values.

It successfully returns a Gaussian variable with a Gaussian PDF and with the specified mean value. However, the problem is its variance. I'm stuck at this point, because I don't know how to change its variance to the user specified value.

This is my code (incomplete for now; the parameter "Variance" is ignored):

template &lt;class T&gt;
T Random::GetGaussian(T Mean /*= 0*/, T Variance /*= 1*/)
{
    T MeanOfSum = NUM_GAUSSIAN_SUMS / static_cast&lt;T&gt;(2);
    T Rand = 0;
    for (uint64_t i=0; i&lt;NUM_GAUSSIAN_SUMS; i++)
    {
        Rand += static_cast&lt;T&gt;(rand()) / RAND_MAX;
    }
    return Rand - (MeanOfSum - Mean);
}


Assume that NUM_GAUSSIAN_SUMS is 100, and RAND_MAX is 32767.

I want to change variance of the random variable according to the parameter of the function. My question is, how can I change variance of this random variable? How can I do it?
Your initial algorithm creates a random variable that's uniformly distributed between 0 and 1. The variance of that is 1/12. If you sum NUM_GAUSSIAN_SUMS instances of that the variance will be NUM_GAUSSIAN_SUMS/12. In order to get to a target variance, V, you need to multiply the summed random variable with sqrt(V*12/NUM_GAUSSIAN_SUMS).

As a side note, a template will work reasonable well for floats and doubles but there will be significant numerical problems with any fixed point type.