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:
This program demonstrates various ways to generate random numbers in Fortran:
We use the
random_number
subroutine to generate random real numbers between 0 and 1.To generate random integers between 0 and 99, we multiply the random real by 100 and convert to an integer.
We generate random floats between 5.0 and 10.0 by scaling and shifting the output of
random_number
.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:
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.