section 7.8.7: Random Number Generation

There is a typo in some printings; the code for returning a floating-point random number in the interval [0,1) should be

	#define frand() ((double) rand() / (RAND_MAX+1.0))

If you want to get random integers from M to N, you can use something like

	M + (int)(frand() * (N-M+1))

``[Setting] the seed for rand'' refers to the fact that, by default, the sequence of pseudo-random numbers returned by rand is the same each time your program runs. To randomize it, you can call srand at the beginning of the program, handing it some truly random number, such as a value having to do with the time of day. (One way is with code like

	#include <stdlib.h>
	#include <time.h>

srand((unsigned int)time((time_t *)NULL));
which uses the time function mentioned on page 256 in appendix B10.)

One other caveat about rand: don't try to generate random 0/1 values (to simulate a coin flip, perhaps) with code like

	rand() % 2
This looks like it ought to work, but it turns out that on some systems rand isn't always perfectly random, and returns values which consistently alternate even, odd, even, odd, etc. (In fact, for similar reasons, you shouldn't usually use rand() % N for any value of N.) A good way to get random 0/1 values would be
	(int)(frand() * 2)
based on the other frand() examples above.

Read sequentially: prev up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback