1 #include "Random.h"
2 
3 #include <boost/date_time/posix_time/posix_time.hpp>
4 #include <boost/thread/mutex.hpp>
5 
6 namespace {
7     GeneratorType gen; // the one random number generator driving the distributions below
8 
9     static boost::mutex s_prng_mutex;
10 }
11 
Seed(unsigned int seed)12 void Seed(unsigned int seed) {
13     boost::mutex::scoped_lock lock(s_prng_mutex);
14     gen.seed(static_cast<boost::mt19937::result_type>(seed));
15 }
16 
ClockSeed()17 void ClockSeed() {
18     boost::mutex::scoped_lock lock(s_prng_mutex);
19     boost::posix_time::time_duration diff = boost::posix_time::microsec_clock::local_time().time_of_day();
20     gen.seed(static_cast<boost::mt19937::result_type>(diff.total_milliseconds()));
21 }
22 
SmallIntDist(int min,int max)23 SmallIntDistType SmallIntDist(int min, int max) {
24     boost::mutex::scoped_lock lock(s_prng_mutex);
25     return SmallIntDistType(gen, boost::uniform_smallint<>(min, max));
26 }
27 
IntDist(int min,int max)28 IntDistType IntDist(int min, int max) {
29     boost::mutex::scoped_lock lock(s_prng_mutex);
30     return IntDistType(gen, boost::uniform_int<>(min, max));
31 }
32 
DoubleDist(double min,double max)33 DoubleDistType DoubleDist(double min, double max) {
34     boost::mutex::scoped_lock lock(s_prng_mutex);
35     return DoubleDistType(gen, boost::uniform_real<>(min, max));
36 }
37 
GaussianDist(double mean,double sigma)38 GaussianDistType GaussianDist(double mean, double sigma) {
39     boost::mutex::scoped_lock lock(s_prng_mutex);
40     return GaussianDistType(gen, boost::normal_distribution<>(mean, sigma));
41 }
42 
RandSmallInt(int min,int max)43 int RandSmallInt(int min, int max)
44 { return (min == max ? min : SmallIntDist(min,max)()); }
45 
RandInt(int min,int max)46 int RandInt(int min, int max)
47 { return (min == max ? min : IntDist(min, max)()); }
48 
RandZeroToOne()49 double RandZeroToOne()
50 { return DoubleDist(0.0, 1.0)(); }
51 
RandDouble(double min,double max)52 double RandDouble(double min, double max)
53 { return (min == max ? min : DoubleDist(min, max)()); }
54 
RandGaussian(double mean,double sigma)55 double RandGaussian(double mean, double sigma)
56 { return GaussianDist(mean, sigma)(); }
57