47 static void initRand(std::mt19937* which = 0,
const bool random =
false,
const int seed = 23423);
53 static inline double rand(std::mt19937* rng = 0) {
57 const double res = double((*rng)() / 4294967296.0);
58 #ifdef DEBUG_RANDCALLS
60 if (myCallCount[rng] == myDebugIndex) {
61 std::cout <<
"DEBUG\n";
63 std::stringstream stream;
64 stream <<
" rng" << myRngId.find(rng)->second <<
" rand call=" << myCallCount[rng] <<
" val=" << res <<
"\n";
65 std::cout << stream.str();
71 static inline double rand(
double maxV, std::mt19937* rng = 0) {
72 return maxV *
rand(rng);
76 static inline double rand(
double minV,
double maxV, std::mt19937* rng = 0) {
77 return minV + (maxV - minV) *
rand(rng);
81 static inline int rand(
int maxV, std::mt19937* rng = 0) {
85 unsigned int usedBits = maxV - 1;
86 usedBits |= usedBits >> 1;
87 usedBits |= usedBits >> 2;
88 usedBits |= usedBits >> 4;
89 usedBits |= usedBits >> 8;
90 usedBits |= usedBits >> 16;
95 result = (*rng)() & usedBits;
96 }
while (result >= maxV);
101 static inline int rand(
int minV,
int maxV, std::mt19937* rng = 0) {
102 return minV +
rand(maxV - minV, rng);
106 static inline long long int rand(
long long int maxV, std::mt19937* rng = 0) {
107 if (maxV <= std::numeric_limits<int>::max()) {
108 return rand((
int)maxV, rng);
113 unsigned long long int usedBits = maxV - 1;
114 usedBits |= usedBits >> 1;
115 usedBits |= usedBits >> 2;
116 usedBits |= usedBits >> 4;
117 usedBits |= usedBits >> 8;
118 usedBits |= usedBits >> 16;
119 usedBits |= usedBits >> 32;
122 long long int result;
124 result = (((
unsigned long long int)(*rng)() << 32) | (*rng)()) & usedBits;
125 }
while (result >= maxV);
130 static inline long long int rand(
long long int minV,
long long int maxV, std::mt19937* rng = 0) {
131 return minV +
rand(maxV - minV, rng);
135 static inline double randNorm(
double mean,
double variance, std::mt19937* rng = 0) {
139 u =
rand(2.0, rng) - 1;
140 const double v =
rand(2.0, rng) - 1;
142 }
while (q == 0.0 || q >= 1.0);
143 return (
double)(mean + variance * u * sqrt(-2 * log(q) / q));
148 static inline const T&
150 assert(v.size() > 0);
151 return v[
rand((
int)v.size(), rng)];
159 std::ostringstream oss;
165 static void loadState(
const std::string& state, std::mt19937* rng = 0) {
169 std::istringstream iss(state);
178 #ifdef DEBUG_RANDCALLS
179 static std::map<std::mt19937*, int> myCallCount;
180 static std::map<std::mt19937*, int> myRngId;
181 static int myDebugIndex;