As far as I know, there is no pseudo random number generator for c. I don't know much about probability and statistics, but does anyone else know of a method or function (or perhaps a library that contains a function) that returns a pseudo random scalar value drawn from a normal distribution with mean 0 and standard deviation 1?
I was able to find some code on the internet, but it uses the rand() function, which I heard is not all that random in c.
Here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
/* Generate a normal random variable with mean 0 and
standard deviation
of 1. To adjust to some other distribution, multiply by the
standard
deviation and add the mean. Box-Muller method
note: rand() is a function that returns a uniformly
distributed random
number from 0 to RAND_MAX
*/
double randn()
{
static double V2, fac;
static int phase = 0;
double S, Z, U1, U2, V1;
if (phase)
Z = V2 * fac;
else
{
do {
U1 = (double)rand()/ RAND_MAX;
U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1);
fac = sqrt (-2 * log(S) / S);
Z = V1 * fac;
}
phase = 1 - phase;
return Z;
}
Any help would be greatly appreciated.
Thank you.