Pseudo-Randomness

Most computers cannot generate truly random numbers.

The functions random() and drand48() are actually pseudo-random number generators.

This means that they use complex mathematical functions whose values, when viewed in a sequence, look fairly random. They won't pass advanced statistical tests for real randomness, but they're close enough for most work.

However, because they're mathematical functions, they're predictable.
Every time a program is started from scratch, these functions will return the exact same sequence of numbers, which can mean that your supposedly random program behaves exactly the same way each time it's run.

This can be avoided by using the random function's seed function, which gives the function a different starting point to use, instead of the default.

Both of these functions take an integer seed-value. In order to get a different sequence of random numbers each time you run your program, this seed-value must always be different.
A quick & easy way to do this is to use the current time:

    #include <time.h>

    srandom(time(0));
    drand48(time(0));

Note 1

In some cases, you might want to be able to exactly reproduce a particularly interesting run of your program. Using the same seed-value will result in the same sequence of random numbers, so if you print out & record the seed number used whenever your program starts, you can plug that particular seed in again later to reproduce the run.

Note 2

Using the current time (in seconds, from time(), or in microseconds, from gettimeofday()) is a useful way to get one random number, since the exact time that a program will be run is generally random. But, this cannot be used more than once in a program, because once the program starts, the time values returned will form a fairly predictable sequnce.



next