# Creating pseudo-random numbers with rand()

In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made:

"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits)."

Random-number generation is a complex topic. The Numerical Recipes in C book (see reference above) provides an excellent discussion of practical random-number generation issues in Chapter 7 (Random Numbers).

Source: http://linux.die.net/man/3/rand

## Example: randomly sleep between 1 to 3 seconds

int sleepTime = 0; srand(time(NULL)); // set the seed sleepTime = 1 + (int) (2000000 * (rand() / (RAND_MAX + 1.0))); sleepTime += 1000000; #ifdef DBG fprintf(stderr, "\nDBG: sleepTime: %d\n", sleepTime); #endif

### Sample output (20 iterations):

DBG: sleepTime: 2456105

DBG: sleepTime: 2592463

DBG: sleepTime: 1038192

DBG: sleepTime: 2758857

DBG: sleepTime: 1907930

DBG: sleepTime: 2341565

DBG: sleepTime: 1779641

DBG: sleepTime: 1212501

DBG: sleepTime: 2919997

DBG: sleepTime: 1078757

DBG: sleepTime: 1787229

DBG: sleepTime: 2222557

DBG: sleepTime: 1662914

DBG: sleepTime: 1094766

DBG: sleepTime: 2805637

DBG: sleepTime: 2956669

DBG: sleepTime: 1098023

DBG: sleepTime: 1825648

DBG: sleepTime: 1256375

DBG: sleepTime: 1976356