Real random number generator: a basic gaussian distribution

'gauss_rand_simple()' is a function written in language C which return a real (double) value according to a gaussian distribution, that is mean 0 and variance 1.

        #include <stdlib.h>
        #include <time.h> //necessary for time_t variable
        #include <math.h>
        #include <stdio.h>     
      
     
       #define NUM 100; 
       #define NSUM 25

         double gauss_rand_simple() {
           double x = 0;
           int i;
           for(i = 0; i < NSUM; i++)
               x += (double)rand() / RAND_MAX;
               x -= NSUM / 2.0;
               x /= sqrt(NSUM / 12.0);
               return x;
           }

       }

    
        int main(int argc, char* argv[]) {
           time_t t;
           srand((unsigned int) time(&t));
           double val = 0;

           for (int i=0; i < 10; ++i) {      
                val = gauss_rand_simple();
                printf("%f\n",  val);
           }
           return 0;
        }


  • for an explanation of rand, RAND_MAX, srand(), see my post on Uniform distribution.
  • this program generates ten real number with mean '0' and variance '1', that is ten real numbers centered around 0 and that differ by mean '1' from '0'
# ./a.out
0.185610
0.484195
2.535164
0.901258
-0.896405
0.301616
-0.491236
-0.524129
-0.236051
-0.519718


It is also possible generate a Gaussian distribution given a mean and a variance. We will see this in a later post.

Commenti

Post popolari in questo blog

Real Random number generator: Uniform distribution