Pseudo-Random Numbers in C
stdlib.h -
rand(),
srand(),
RAND_MAX
srand( seed); // initialize rand()
r = rand(); // generate pseudo-random integer from 0 to RAND_MAX
time.h -
time()
time(0) is current time in seconds since 1970
Examples:
double d; int r, seed = time(0);
srand(seed); // just once, at beginning of main
r = rand(); // 0 ≤ r ≤ RAND_MAX
r = rand() % (b-a+1) + a; // range of int, a ≤ r ≤ b
d = (rand()/(double)RAND_MAX)*(b-a) + a; // range of double, a ≤ d ≤ b
C99 7.20.2.2 Example:
The following functions define a portable implementation of rand() and srand():
static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
next = seed;
}