Wednesday, March 18, 2009

Generate numbers in Gaussian (normal) Distribution in C

C doesn't have direct function to generate numbers which follow Gaussian Distribution. Here is how one an do this. We can use the cumulative distribution function of the Normal Distribution to generate the required. The code below illustrates how to generate a point between -3 to +3 with resolution of .005 and which follows the standard Normal Distribution. The code can accordingly be changed for other normal distribution and other range. step size multiplied by the no of points/2 in CDF array gives the range.



#include "stdio.h" // change accordingly
#include "stdlib.h"
#include "math.h"

double CDF[1202];//gloabal array which contains the CDF of the normal distribution

double generateAWGN(){
double temp;
int i=0,j=0;
temp = CDF[1]+(CDF[1201]-CDF[1])*rand()/RAND_MAX;//uniformly distributed temp
if(temp>.5)
{
for(i=602;i<1202;i++){>=temp){
return (i-601)*.005;
}
}
}
else
{
for(j=600;j>0;j--){
if(CDF[j]<=temp) return (j-601)*.005; } } } int main(int argc, char *argv[]) { int i=0; double step = .005,tmp,avg,pns; double past_tmp = .399, extra,a; CDF[601]=.5;//mean has CDF .5 for(i=1;i<=600;i++) { tmp = .399*step*exp(-((step*i)*(step*i))/2);//value at step*i of pdf extra = (past_tmp-tmp)*step*.5; past_tmp = tmp; CDF[601+i] = CDF[601+i-1]+tmp+extra; CDF[601-i] = CDF[601-i+1]-tmp-extra; } //printf("%f and %f \n",CDF[1201],CDF[1]); printf("the elements which follow gaussina distribution\n"); for(i=0;i<1000;i++) { pns = generateAWGN(); printf("%f\n",pns); avg = pns/1000; } printf("average of the elements = %f",avg); }

1 comment: