next up previous
Next: Timers Up: intro_C Previous: Variable-size multi-dimensional arrays

Random Numbers

There are several random number generators available in the C library. For modern implementations, the recommended one is int rand(void);, which returns a random integer between 0 and RAND_MAX (#include <stdlib.h>). Use void srand(unsigned int seed); to seed the generator. Ideally you want a different seed for each invocation of the program. One way to do this is to use srand(getpid()); where getpid() returns the ID number of the current process (#include <unistd.h>). A better seed can be obtained by combining getpid() with the Unix time (#include <time.h>--see next section) and the parent ID: (int) time(NULL) % getpid() + getppid().

Massimo Ricotti 2009-01-26