A.1.3    Random Number Generator

    Often problems arise that require generation of a random number or a series of random numbers.  Fortran 90 contains a subprogram for this purpose.  The random number generator produces a pseudorandom (it is impossible to have an algorithm that is truly random) number distributed between 0 and 1.   The random number generator is initiated by the subprogram RANDOM_SEED.  RANDOM_SEED, when called, initializes the random number generator.  Three arguments are possible when calling RANDOM_SEED.

    CALL RANDOM_SEED (SIZE, GET, PUT)

If called without an argument then RANDOM_SEED restarts the number generator.  If an argument is present it queries the random number generator.  SIZE will output the number of integers used to hold the seed.  GET  will give the current value of the seed.  PUT allows for control of the seed.  PUT is the only command that provides input.  It indicates the value to be used as the initial seed for the random number generator.  PUT must be a one-dimensional array.  random seed only needs to be called once in a program.  It is used to generate the first random number.  Any random numbers generated after the first will use the previous random number as its seed.

    RANDOM_NUMBER is the actual random number generator.  It takes a seed (or more then one if creating an array of random numbers)  and generates a pseudorandom number between 0 and 1.  The  general form is:

    CALL RANDOM_NUMBER(argument)

Argument can be a single variable, an array, or items within an array.  It will contain the pseudorandom number based on the seed generated using RANDOM_SEED.  If an array is given then the array will be filled with random numbers.  Here is an example for generating 5 random numbers using a predetermined seed.

    INTEGER, DIMENSION (1) :: seed = (/3/)
    REAL :: num

    CALL RANDOM_SEED (PUT=seed)

    DO n = 1, 5

        CALL RANDOM_NUMBER(num)

        PRINT *, num

    END DO

This program will generate and print five random numbers.  The first is found using 3 as the seed, and the following ones use the preciously generated number as the seed.  num contains the value of the random number generated and is updated for each loop.  By controlling the seed the random numbers generated will be the same every time.  A compiler will produce the same random number given the same seed.