Random Numbers

Random number generation is easy. You get a random number uniformly distributed between 0 and RAND_MAX (2147483647) by calling rand. For example:

   r = rand ();
   

The include file for rand is stdlib.h

To convert this to a uniformly distributed random number between some low value and some high value, you perform the following:

   r = rand ();
   r1 = (int) (low + ((float) r)/(float)RAND_MAX * high);
   

For example, to get a random number between 1 and 100,

   r = rand ();
   r1 = (int) (1 + ((float) r)/(float)RAND_MAX * 100);
   

However, this will always generate the same sequence of random numbers which isn't much fun (but useful for debugging), so you can call another function to set the random number seed, srand.

   srand (seed_val);
   

If the seed_val is the same, you get the same sequence, so you would like some way to set the seed randomly. This seems like a Catch-22, but you can use the clock to get a random starting point like this:

   struct timeval    timeofday;
   struct timezone   tz;
   long              seed;


   gettimeofday (&timeofday, &tz);
   seed = timeofday . tv_sec + timeofday . tv_usec;
   srand (seed);
   

Remember, you only seed the random generator once when your program starts and after that, it generates a long sequence of numbers which are close to random. If you seed it repeatedly, you will get crummy random numbers, that is, not very random.