Lawrence Technological University
College of Arts and Science
Department of Mathematics and Computer Sciences

Introduction to C, MCS 1142

### Random Numbers

Some considerations for generating random numbers in C programs.

• Random-number generation is a complex topic. The book Numerical Recipes in C, by William H. Press, Brian P. Flannery, Saul A. Teukolsky and William T. Vetterling, covers practical random-number generation issues in Chapter 7. The Art of Computer Programming, by Donald E. Knuth has even more in Volume 2, chapter 3.
• Random-number generation in C usually uses the library functions rand() and srand()
```#include <stdlib.h>
int rand(void);
void srand(unsigned int seed);
```
• The description of rand and srand is the same for most C compilers. The rand() function returns a pseudo-random integer between 0 and RAND_MAX. The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value. If no seed value is provided, the rand() function is automatically seeded with a value of 1. The srand() returns no value.
• A typical older version of rand is on the VAX
```static unsigned int next = 1;
int rand(void)
{
next = next * 1103515245 + 12345;
return (next  & RAND_MAX);
}
```
• This makes a number whose leftmost bits are more random than its rightmost bits.
• Many C compilers have a function random() that rotates the bits and thus makes small numbers more random.
• One solution from Numerical Recipes in C
If you want to generate a random integer between 1 and 10, you should always do it by
```j=1+(int) (10.0*rand()/(RAND_MAX+1.0));
```
and never by anything resembling
```j=1+((int) (1000000.0*rand()) % 10);
```
which uses lower-order bits.
• For one time use
```srand(time(NULL));
```
gives a fairly random result.
• When we want a short series of random numbers all at once. Something like the following should help
```#include <stdlib.h>
#include <time.h>
static unsigned int rand_seed = 1;
int rand_1_10(void)
{
if (rand_seed == 1) {
rand_seed = time(NULL);
srand(rand_seed);
}
return 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));
}
```

Revised May 1, 2003