Random numbers and seeding

Fortran has a random number generator in the language: random_number fills a real array with values between zero and one, and random_seed reads and writes the state it runs from. The pair is small and complete, and the interesting part is the state: a program that never touches it draws a different sequence on every run, and a program that sets it draws the same sequence for ever, which is what a test needs.

RANDOM_NUMBER

call random_number(x) takes a real scalar or array and fills every element with a value in the half-open interval [0, 1). The standard calls the argument the harvest, which is the name in the error message of the last section. The generator is the compiler's, not the standard's: two compilers may give two different sequences from the same seed, and the numbers are not promised to be good for cryptography or for very long simulations.

The file rnd.f90:

program randdemo implicit none integer, allocatable :: seed(:) integer :: n, i real :: x(5), mean, hist(5), r integer :: counts(5) call random_seed(size=n) print '(a,i0)', 'seed size = ', n allocate(seed(n)) call random_number(x) print '(a,5f8.5)', 'at start = ', x seed = 42 call random_seed(put=seed) call random_number(x) print '(a,5f8.5)', 'seed 42 = ', x call random_seed(put=seed) call random_number(x) print '(a,5f8.5)', 'seed 42 again = ', x seed = [(i * 7919, i = 1, n)] call random_seed(put=seed) call random_number(x) print '(a,5f8.5)', 'seed 1,2,3... = ', x seed = 42 call random_seed(put=seed) counts = 0 mean = 0.0 do i = 1, 100000 call random_number(r) mean = mean + r counts(min(5, int(r * 5.0) + 1)) = counts(min(5, int(r * 5.0) + 1)) + 1 end do mean = mean / 100000.0 print '(a,f10.6)', 'mean of 100000 = ', mean hist = real(counts) / 100000.0 print '(a,5f9.4)', 'histogram = ', hist end program randdemo

gfortran -Wall -Wextra -std=f2018 rnd.f90 -o rnd
./rnd

seed size = 8
at start = 0.98390 0.30587 0.34487 0.66482 0.62457
seed 42 = 0.47111 0.11730 0.50207 0.05352 0.03747
seed 42 again = 0.47111 0.11730 0.50207 0.05352 0.03747
seed 1,2,3... = 0.52381 0.11222 0.15396 0.65655 0.64739
mean of 100000 = 0.500387
histogram = 0.1979 0.2007 0.2009 0.2026 0.1980

RANDOM_SEED and its size

random_seed(size=n) asks how many integers the state of this generator needs, and this build answers eight. The size is a property of the implementation, so a program allocates the array rather than declaring it with a constant. Three forms exist: put writes the state, get reads it back into an array, and the call with no arguments does nothing at all.

get is what makes a simulation reproducible after the fact: a program that prints the seed on start and takes one on the command line can rerun the exact same stream from a log line. A state array of eight integers is small enough to write into a file or into a printed line.

Reproducibility

The first line of numbers is the state the program found at start, and it changes on every run: gfortran seeds its generator from the clock when the program begins. The second and third lines are the answer to that: the same seed put twice gives the same five numbers, character for character. The fourth line is a different seed array, a hundred thousand draws later the mean and the histogram agree to three digits.

That is the whole design a simulation needs. A test sets a fixed seed and compares the output; a production run either takes a seed from the environment or lets the clock do it, and prints the state it used so the run can be repeated. Without a printed seed a run that produced an interesting result cannot be reproduced, and a Monte-Carlo program that cannot be reproduced is not a measurement.

A hundred thousand draws

The last two lines are a crude quality check. The mean of a hundred thousand uniform draws is 0.500387, which is within four ten-thousandths of the exact 0.5, and the five buckets each hold about a fifth of the draws, between 0.1979 and 0.2026. A generator with a short period or a bad low bit would show a bucket far from 0.2 or a mean far from 0.5.

A test like this proves very little, and that is worth knowing: it catches a broken generator, not a subtle one. The random numbers this course uses are for simulations and for test data, and for both the quality of the compiler's generator is adequate. A program that needs a specific distribution transforms these uniforms itself, which is the next paragraph of any numerical methods book and not a language feature.

Seeding from the clock

For a run that should differ every time, the usual route is system_clock: ask it for a count of ticks, mix that into every element of the seed array, and put it. A seed array filled with one repeated small integer is a poor choice, because the generator mixes the whole array and two arrays of the same repeated value differ less than a reader expects; filling the elements with different values, as the fourth line does, is the safer sketch.

The output of such a program is different on every run by design, so it is not shown here: a page cannot prove a number that changes. The parts that are shown, a seed put and a sequence drawn, are the same code with a value from the clock instead of the constant.

An integer harvest

The generator fills reals, and an integer argument has no specific:

program badrand implicit none integer :: i call random_number(i) print *, i end program badrand

gfortran -Wall -Wextra -std=f2018 badrand.f90 -o badrand

badrand.f90:4:21:

4 | call random_number(i)
| 1
Error: 'harvest' argument of 'random_number' intrinsic at (1) must be REAL

The word harvest is the standard's name for the argument, and it appears in gfortran's message unchanged. An integer random number is a real multiplied and truncated, or nint(r * n) for a value from one to n; the truncation is the caller's job because only the caller knows the range it wants.

Rules for random numbers

Set the seed in a test and print it in a run. Allocate the seed array from random_seed(size=) rather than guessing its length. Fill it with varied values when the run should differ, and with a constant when it should not. And keep the generation in one place in the program, so that a change of generator is one module rather than fifty call sites.

The numerical lessons after this one use random numbers for test data rather than for algorithms, and the capstone tests of part 14 use them with a fixed seed so that a failure can be reproduced. That is the whole of what a general-purpose course needs from the generator; a program that needs a better one links a library, and the call site is the same.

Exercises

  1. Change the seed to seed = 1 and run the program twice. Do the two runs agree with each other, and with the seed 42 line?
  2. Fill the seed array with the values from system_clock and run the program twice. Which line of the output changes?
  3. Draw a million values and print the mean. Does the error fall by a factor of about three compared with the hundred thousand?
  4. Use random_seed(get=saved) before a block of draws and put=saved after it. What can a program do with that pair that a fixed seed cannot?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does call random_number(x) give for an array x?

    Answer

    Every element a value in [0, 1)

    The harvest takes any real array and fills it.

  2. What does random_seed(size=n) return?

    Answer

    The number of integers the generator state needs

    This build needs eight.

  3. What does this program print? program p implicit none integer, allocatable :: s(:) real :: a(2), b(2) integer :: n call random_seed(size=n) allocate(s(n)) s = 5 call random_seed(put=s) call random_number(a) call random_seed(put=s) call random_number(b) print *, all(a == b) end program p

    Answer

    T

    The same seed put twice reproduces the stream.

  4. Why does the first line of the run differ between two runs?

    Answer

    gfortran seeds the generator from the clock at start

    The state at start is not a constant.

  5. Why allocate the seed array instead of declaring it with a constant size?

    Answer

    The size is a property of the implementation

    Ask with SIZE and allocate what the compiler needs.

  6. What does random_seed() with no arguments do?

    Answer

    Nothing at all

    The three forms are PUT, GET and SIZE.

  7. Why print the seed of a long simulation?

    Answer

    So the run can be repeated from the log

    An unreproducible run is not a measurement.

  8. What does a mean of 0.500387 over 100000 draws tell you?

    Answer

    The generator is roughly uniform; it does not prove quality

    A crude check catches a broken generator, not a subtle one.

  9. What does gfortran report for call random_number(i) with an integer?

    Answer

    Error: 'harvest' argument must be REAL

    The generator produces reals; scaling is the caller's job.

  10. Which seed array is the worst choice for a run that should differ?

    Answer

    Every element the same small integer

    One value repeated differs less than a reader expects.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev