#include "CipresCommlib/util_rand.h" #ifdef __cplusplus #include #include #include using std::time; using std::srand; using std::rand; namespace cipres { extern "C" { #else /*__cplusplus*/ #include #include #include #endif /*__cplusplus*/ /** * Returns a random number in the range [0,upperRange). */ unsigned randInt(unsigned upperRange) { #ifdef NOTDEF /*assert(upperRange > 0);*/ if (upperRange < 2) return 0; const double prob = 1.0/((double) upperRange); double x = randDouble(); unsigned toReturn = upperRange - 1; tl - microsoft C compiler requires that declarations preceed executable statements. #endif double prob; double x; unsigned toReturn; if (upperRange < 2) return 0; prob = 1.0/((double) upperRange); x = randDouble(); toReturn = upperRange - 1; for (; toReturn > 0; --toReturn) { x -= prob; if (x < 0.0) return toReturn; } return 0; } /** sets seed to s (or time if s is 0 or UINT_MAX)*/ unsigned setRandSeed(unsigned s) { if (s == 0 || s == UINT_MAX) s = time(NULL); srand(s); return s; } /** Returns a double from the distribution Uniform[0,1.0) */ double randDouble() { return ((double)rand())/((double) RAND_MAX); } #ifdef __cplusplus } /* end extern "C" */ } /* end namespace cipres */ #endif /*__cplusplus*/