Comment

Part R — Random Numbers

revised: 10/17/2015, 06/15/2017, 07/24/2023


These puzzles involve pseudorandom numbers. Pseudorandom numbers are used in games, in simulation, in testing, and in many other situations. The generator rand() is part of the standard library.

int rand(void)

Include the header file stdlib.h in your source file when you use it.

Each call to rand()returns an integer selected from the range 0..RAND_MAX. On many systems, RAND_MAX is 32767, but on some systems it is much higher.

Ideally, rand() is like throwing a 32768-sided die. The return value is in the range 0 to 32767, but the particular value is seemingly unpredictable from throw to throw.

Actually, rand() uses an algorithm and so the integers it returns are completly predictable. If you know the algorithm and the previous value returned, the next value can easily be calculated. Because they are predictable, the numbers are called pseudorandom. But for many purposes the numbers are scrambled up enough that they can be used as random numbers. rand() is not suitable for cryptography or security applications.

The function srand() initializes rand().

int srand( unsigned int seed )

The seed starts the random number generator at an integer of your choice. From then on, the sequence is completely determined by the algorithm. Everytime you start the random number generator with the same seed, you get the same sequence.

To get a different sequence of pseudo-random numbers each time you run a program, start each run with a different seed. Without initialization, rand() produces the same stream of pseudo-random numbers every time it is used. This can be desirable since sometimes you wish to test different algorithms using the same sequence of (pseudo-)random events. For example, to compare two sorting algorithms you would want to use the same sequence of unsorted numbers for each.



Next Page         Home