random.cpp
00001 #include "random.h"
00002 #include <stdlib.h>
00003 #include <cmath>
00004 #ifdef _MSC_VER
00005 # include <sys/timeb.h>
00006 # include <sys/types.h>
00007 #else
00008 # include <sys/time.h>
00009 #endif
00010
00011 #ifdef WIN32
00012 static long int random()
00013 {
00014 return rand();
00015 }
00016
00017 static void srandom(unsigned int seed)
00018 {
00019 return srand(seed);
00020 }
00021 #endif
00022
00023 namespace util
00024 {
00025
00026 void sran(unsigned int seed)
00027 {
00028 return ::srandom(seed);
00029 }
00030
00031 long int random()
00032 {
00033 return ::random();
00034 }
00035
00036 long int random(long int n)
00037 {
00038 return random() % n;
00039 }
00040
00041 double ran(double M)
00042 {
00043 int i = ::random();
00044 return M*(double)i/(double)RAND_MAX;
00045 }
00046
00047 double gaussRan(double mean, double sigma)
00048 {
00049 static float y2 = 0;
00050 static bool cached = false;
00051 if(!cached)
00052 {
00053 float x1, x2, w, y1;
00054 do
00055 {
00056 x1 = ran(2.0) - 1.0;
00057 x2 = ran(2.0) - 1.0;
00058 w = x1*x1 + x2*x2;
00059 } while(w >= 1.0);
00060
00061 w = std::sqrt((-2.0*std::log(w))/w);
00062 y1 = x1*w;
00063 y2 = x2*w;
00064 cached = true;
00065 return y1*sigma + mean;
00066 }
00067 else
00068 {
00069 cached = false;
00070 return y2*sigma + mean;
00071 }
00072 }
00073
00074 unsigned int sran_time()
00075 {
00076 #ifdef _MSC_VER
00077 struct _timeb t;
00078 _ftime(&t);
00079 unsigned int seed = t.millitm + t.time*1000;
00080 #else
00081 struct timeval tv;
00082 struct timezone tz;
00083 gettimeofday(&tv, &tz);
00084 unsigned int seed = tv.tv_usec + tv.tv_sec*1000000;
00085 #endif
00086 sran(seed);
00087 return seed;
00088 }
00089
00090 };
00091