/* * rand.c: randomize(), urand(), irand(), erand(), grand() * * urand: returns uniform pseudo-random double in the range [0.0, 1.0) * irand: returns uniform pseudo-random integer in the range [1, n] * erand: returns exponentially distributed pseudo-random double with mean 1 * grand: returns gaussian distributed double with mean 0 and variance 1 * * Before the first call to any of these routines, the random seed should * be initialized directly using srand() or randomly using randomize(). */ #include #include #include #include /* * RAN macro returns pseudo-random double in the range [0.0, 1.0) */ #ifdef RAND_MAX # define RAN (rand()/( (double) RAND_MAX + 1)) #else # define RAN (rand()/2147483648.0) /* / 2**31 */ #endif /* * randomize: initialize seed from time-of-day */ void randomize( void) { srand( (unsigned) time( (time_t *) NULL) ); } /* * urand: returns uniform pseudo-random double in the range [0.0, 1.0) */ double urand( void) { return RAN; } /* * irand: returns uniform pseudo-random integer in the range [1, n] */ int irand( int n) { return 1 + (int) (n * RAN); } /* * erand: returns exponentially distributed pseudo-random double with mean 1 */ double erand( void) { return -log(1.0 - RAN); } /* * grand: returns gaussian distributed pseudo-random double * with mean 0 and variance 1 */ double grand( void) { int i; double r = -6.0; for( i = 0; i < 12; ++i) r += RAN; return r; }