The Cuik KD-Tree Library


random.c

Go to the documentation of this file.
00001 #include "random.h"
00002 
00003 #include <sys/types.h>
00004 #include <time.h>
00005 #include <stdlib.h>
00006 #include <math.h>
00007 
00018 void randomReset()
00019 {
00020   srand((unsigned int)time(NULL));
00021   rand();
00022   rand();
00023 }
00024 
00025 void randomSet(unsigned int seed)
00026 {
00027   srand(seed);
00028   rand(); /*useful to avoid first rands to be almost equals*/
00029   rand();
00030 
00031 }
00032 
00033 double randomDouble()
00034 {
00035   return((double)rand()/(double)RAND_MAX);
00036 }
00037 
00038 double randomNormal()
00039 {
00040   static int oneCached=0;
00041   double x1,x2,w;
00042   double y1;
00043   static double y2;
00044 
00045   if (oneCached)
00046     {
00047       oneCached=0;
00048       return(y2);
00049     }
00050   else
00051     {
00052       do {
00053         x1=2.0*randomDouble()-1.0;
00054         x2=2.0*randomDouble()-1.0;
00055         w=x1*x1+x2*x2;
00056       } while (w>=1.0);
00057       
00058       w=sqrt((-2.0*log(w))/w);
00059       y1=x1*w;
00060       y2=x2*w;
00061  
00062       oneCached=1;
00063       return(y1);
00064     }
00065 }