00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 
00018 
00019 
00020 
00021 
00022 
00023 #ifndef __AN_RANDOM_H
00024 #define __AN_RANDOM_H
00025 
00026 #include <cmath>
00027 #include <cstdlib>
00028 
00033 namespace An
00034 {
00036 
00037     class FastRandom
00038     {
00039     private:
00040         unsigned long randx; 
00041     
00042     public:
00044         FastRandom(void) { randx = 0; }
00046         void setSeed(unsigned long seed) { randx = seed; }
00048         unsigned long get(void) { return (randx = randx*1103515245 + 12345) & 0x7fffffff; }
00050         double getRange(double range) { return (static_cast<double>(get()) * range) / 2147483648.0; }
00051     };
00052     
00054 
00055     inline double uniformRand(void)
00056     {
00057         return double(rand())/RAND_MAX;
00058     }
00059     
00061     struct UniformRand
00062     {
00063         double from; 
00064         double to;
00065         
00067         UniformRand(double from = 0.0, double to = 1.0) { this->from = from; this->to = to; }
00068         
00070         double operator()() const { return from + (to-from)*uniformRand(); }
00071     };
00072     
00074 
00075     inline unsigned intRand(unsigned max)
00076     {
00077         if (max)
00078             return rand() % max;
00079         else
00080             return 0;
00081     }
00082     
00084 
00085     inline bool boolRand(double prob = 0.5)
00086     {
00087         return uniformRand() < prob;
00088     }
00089     
00091 
00092     inline double gaussianRand(double mean, double sigm)
00093     {
00094         
00095         
00096         
00097         
00098         
00099         double r, x, y;
00100         
00101         
00102         do
00103         {
00104             x = uniformRand()*2 - 1;
00105             y = uniformRand()*2 - 1;
00106             r = x*x + y*y;
00107         }
00108         while (r > 1.0 || r == 0);
00109         
00110         
00111         return sigm * y * sqrt (-2.0 * log(r) / r) + mean;
00112     }
00113 }
00114 
00115 #endif