6

I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5. but how do i modify this code so that i can denerate gaussian random numbers of any given mean and variance?

#include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

double drand()   /* uniform distribution, (0..1] */
{
  return (rand()+1.0)/(RAND_MAX+1.0);
}

double random_normal() 
 /* normal distribution, centered on 0, std dev 1 */
{
  return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}

int main()
{

  int i;
  double rands[1000];
  for (i=0; i<1000; i++)
  rands[i] = 1.0 + 0.5*random_normal();
  return 0;

}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Divya
  • 61
  • 1
  • 2

2 Answers2

10

I have a code here which generates random numbers having a mean 0f 1 and std deviation of 0.5. but how do i modify this code so that i can denerate gaussian random numbers of any given mean and variance?

If x is a random variable from a Gaussian distribution with mean μ and standard deviation σ, then αx+β will have mean αμ+β and standard deviation |α|σ.

In fact, the code you posted already does this transformation. It starts with a random variable with mean 0 and standard deviation 1 (obtained from the function random_normal, which implements the Box–Muller transform), and then transforms it to a random variable with mean 1 and standard deviation 0.5 (in the rands array) via multiplication and addition:

double random_normal();  /* normal distribution, centered on 0, std dev 1 */

rands[i] = 1.0 + 0.5*random_normal();
nibot
  • 14,428
  • 8
  • 54
  • 58
  • 1
    A typo: `αx+β` has mean `αμ+β`, not `μ+β`, and the standard deviation is better expressed as `|α|σ` to take into account the possibility that `α` is negative: standard deviation cannot be a negative number. – Dilip Sarwate Mar 22 '12 at 17:12
3

There are several ways to do this- all of which basically involve transforming/mapping your uniformly distributed values to a normal/gaussian distribution. A Ziggurat transformation is probably your best bet.

One thing to keep in mind- the quality of your end distribution is only as good as your RNG, so be sure to use a quality random number generator (e.g.- Mersenne twister) if the quality of the generated values is important.

MarkD
  • 4,864
  • 5
  • 36
  • 67