_           _                 
 | |_ ___  __| |____  ___ _   _ 
 | __/ _ \/ _` |_  / / _ \ | | |
 | ||  __/ (_| |/ / |  __/ |_| |
  \__\___|\__,_/___(_)___|\__,_|

Generating normally distributed random floating point numbers in C

The following C code used the Box Muller Transform to generate 1000 pairs of normally distributed random floating point values.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    double a, u, v, s=0, z0, z1;

    srand(time(NULL));

    for (int count = 0 ; count < 1000 ; ++count)
    {
        s = 0;
        while(s >= 1 || s==0)
        {
            u = (2.0 * (double)rand() / (double)RAND_MAX) - 1.0;
            v = (2.0 * (double)rand() / (double)RAND_MAX) - 1.0;
            s = u*u + v*v;
        }

        a = sqrt((-2*log(s))/s);
        z0 = u*a;
        z1 = v*a;
        printf("%lf,%lf\n", z0, z1);
    }

    return 0;
}

The program output can be piped into a CSV file as follows:

gcc norm.c -o norm -lm
./norm > points.csv

To create a scatter plot of the values in Octave:

m = csvread('points.csv');
scatter(m(:,1),m(:,2))

insert alt text here