Sometimes it is useful in a FORTRAN program to be able to generate "random" numbers, that is, a sequence of numbers that appear to have no discernible pattern. As these are being genetated by a program, they are not, of course, really random; if we started over, we would produce the same sequence of numbers exactly. Sometimes these are called "pseudo-random" numbers. (To produce truly random numbers requires the use of a physical process such as radioactive decay.)
How do we generate random numbers?
FORTRAN provides intrinsic subroutines to generate pseudo-random numbers:
RANDOM_SEED
This initializes the random number generator. Internally, there is a starting value known as the seed. If we say
CALL RANDOM_SEED
we will have a default starting value chosen for us. If we want to choose our own seed value, we can say
CALL RANDOM_SEED(N)
where N is an Integer. This makes it possible to generate the same sequence of pseudo-random values more than once.
RANDOM_NUMBER(X)
This returns a value in the Real variable X, where 0.0 <= X < 1.0.
To use these: Early in your program, use
CALL RANDOM_SEED
to start the random number generator, and later, use
CALL RANDOM_NUMBER(X)
to obtain the next random value in the Real variable X.
Can we do this for ourselves?
Here is a function borrowed from another FORTRAN textbook. It should give you some idea of how random numbers are generated. It is not by any means the same as the library's facility.
Function RANDOM(Seed) Implicit None Real :: Random Integer :: Seed Integer :: OldSeed = 0 Integer, Parameter :: C1 = 19423 Integer, Parameter :: C2 = 811 Save OldSeed If (OldSeed .EQ. 0) OldSeed = Seed OldSeed = Mod(C1 * OldSeed, C2) RANDOM = 1.0 * OldSeed / C2 End Function RANDOM
This function generates pseudo-random Real numbers between 0.0 and 1.0. The values are not really random; the sequence depends on the initial value of Seed.
To use this: Select a starting value for Seed and use lines such as
X = RANDOM(Seed)
to obtain the next value in the Real variable X.
If we wanted to generate a large number of values, this function would not be a good choice, as it will produce only 811 different values in all.
Notice the use of "Save". Each time the function is executed, we have a new value of OldSeed, which is stored to be used next time.
If we wanted random Integer values, we could just use the OldSeed values.
The numbers used here (19423 and 811) are carefully selected.