rand

The rand function returns a new pseudo-random number each time it is called. The numbers are generated by an algorithm and are intended to look like completely random, but are in fact derived from a very long sequence (that is why the name pseudo-random). Different implementations of the C library are allowed to used different algorithms for random generation, so the exact method used is dependent on the implementation.

The rand function requires no arguments. Its return value is the pseudo-random integer number that has been generated. The maximum number returned by the function is defined as RAND_MAX in stdlib.h.

The first use of rand should be preceded by a call to srand, a function used to initialize the sequence of random numbers. The number provided to srand is known as the seed of the sequence of (pseudo) random numbers.

An important note about the rand function is that, since the exact algorithm used is not standard, you cannot guarantee that the results will be the same in different architectures. This limits the portability of programs using rand in the sense that the results might be different even if the same random seed is used. A possible solution for this problem involves implementing a random generator (many of them are widely available in source form on the Internet).

The following code shows an example of rand in use:

#include <stdlib.h>
#include        <stdio.h>

int main()
{
        int i;
        int num_elements = 10;
        srand(0);
        rand();
        for (i=0; i<num_elements; i++) {
                printf("the value is %d\n", rand());
        }
        return 0;
}

The output of this program is:

the value is 1481765933
the value is 1085377743
the value is 1270216262
the value is 1191391529
the value is 812669700
the value is 553475508
the value is 445349752
the value is 1344887256
the value is 730417256
the value is 1812158119
Article created on 2008-08-19 22:07:48

Post a comment