Random Numbers in Co-array Fortran

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

Our program demonstrates the generation of random numbers in Co-array 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, ",", I0)', i, int(r * 100)

    ! Generate a random float between 0.0 and 1.0
    call random_number(r)
    print *, r

    ! Generate random floats between 5.0 and 10.0
    call random_number(r)
    print '(F7.3, ",", F7.3)', (r * 5) + 5, (r * 5) + 5

    ! Set a known seed for reproducible results
    call random_seed(put=[42, 1024])
    
    call random_number(r)
    print '(I0, ",", I0)', int(r * 100), int(r * 100)

    ! Using the same seed will produce the same sequence
    call random_seed(put=[42, 1024])
    
    call random_number(r)
    print '(I0, ",", I0)', int(r * 100), int(r * 100)

end program random_numbers

In this program, we use Fortran’s intrinsic random_number subroutine to generate pseudorandom numbers. Here’s a breakdown of the code:

  1. We use random_number(r) to generate a random real number between 0.0 and 1.0.

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

  3. We demonstrate generating random floats in different ranges, such as between 5.0 and 10.0.

  4. To set a known seed for reproducible results, we use random_seed(put=[42, 1024]). This is similar to creating a new random source with a specific seed in other languages.

  5. We show that using the same seed produces the same sequence of random numbers.

To compile and run the program:

$ gfortran -o random_numbers random_numbers.f90
$ ./random_numbers
68,56
0.8090228139659177
5.840,6.937
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 consistent due to the fixed seed.

Fortran’s random number generation is relatively simple compared to some other languages, but it provides the basic functionality needed for many applications. For more advanced random number generation, you might need to use external libraries or implement specific algorithms yourself.