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 <class T>
T Random::GetGaussian(T Mean /*= 0*/, T Variance /*= 1*/)
{
T MeanOfSum = NUM_GAUSSIAN_SUMS / static_cast<T>(2);
T Rand = 0;
for (uint64_t i=0; i<NUM_GAUSSIAN_SUMS; i++)
{
Rand += static_cast<T>(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?