Random Numbers in Fortran

Here’s the translation of the random numbers example from Go to Fortran, formatted in Markdown suitable for Hugo:

Our program will demonstrate how to generate random numbers in Fortran. Here’s the full source code:

program random_numbers
    use, intrinsic :: iso_fortran_env, only: real64
    implicit none
    
    real(real64) :: r
    integer :: i
    
    ! Generate random integers between 0 and 99
    call random_number(r)
    i = int(r * 100)
    print '(I0, A)', i, ","
    
    call random_number(r)
    i = int(r * 100)
    print '(I0)', i
    
    ! Generate a random float between 0.0 and 1.0
    call random_number(r)
    print '(F10.8)', r
    
    ! Generate random floats between 5.0 and 10.0
    call random_number(r)
    print '(F10.8, A)', (r * 5) + 5, ","
    
    call random_number(r)
    print '(F10.8)', (r * 5) + 5
    
    ! Set a known seed for reproducible results
    call random_seed(put=[42, 1024])
    
    call random_number(r)
    i = int(r * 100)
    print '(I0, A)', i, ","
    
    call random_number(r)
    i = int(r * 100)
    print '(I0)', i
    
    ! Resetting the seed to get the same sequence
    call random_seed(put=[42, 1024])
    
    call random_number(r)
    i = int(r * 100)
    print '(I0, A)', i, ","
    
    call random_number(r)
    i = int(r * 100)
    print '(I0)', i
    
end program random_numbers

This program demonstrates various ways to generate random numbers in Fortran:

  1. We use the random_number subroutine to generate random real numbers between 0 and 1.

  2. To generate random integers between 0 and 99, we multiply the random real by 100 and convert to an integer.

  3. We generate random floats between 5.0 and 10.0 by scaling and shifting the output of random_number.

  4. Fortran allows setting a seed for reproducible results. We demonstrate this by setting a seed, generating some numbers, then resetting the seed to get the same sequence.

To run the program, save it as random_numbers.f90 and compile it with a Fortran compiler:

$ gfortran random_numbers.f90 -o random_numbers
$ ./random_numbers
68,56
0.80902281
5.84012502,6.93705630
94,49
94,49

Note that the actual numbers generated may be different when you run the sample, except for the last two lines which should be identical due to the seed being reset.

Fortran’s intrinsic random number generator is quite basic. For more advanced random number generation, including different distributions or algorithms, you might want to consider using external libraries like the Fortran Standard Library (stdlib) or RANDOM_LIB.