Real random numbers in Fortran

Fortran does random numbers really nicely, to the point where they actually seem random. Below is a piece of code which generates a series of 10 random numbers, which are different each time the program is run. It uses a seed value extracted from the Fortran subroutine date_and_time(), which returns an array containing eight pieces of data: from years to milliseconds. All eight pieces of data returned allow for the creation of a unique seed value for the random number generator.

program randomEG
implicit none

integer :: k, i, n=10
real :: r
integer, dimension(8) :: values 
! Declare an assumed shape, dynamic array
integer, dimension(:), allocatable :: seed

! gfortran subroutine to return date and time information 
! from the real time system clock. Works down to milliseconds 
! and stores the eight return values in array values.
call date_and_time(VALUES=values)

! restart the state of the pseudorandom number generator
! k = minimum size of seed (12 on my system)
call random_seed(size=k)

! allocate memory to seed
allocate(seed(k))

! assign information in values to seed
seed(:) = values(:)

! seed the random number generator
call random_seed(put=seed)

do i=1,n
    call random_number(r)
    print *, r
end do

end program randomEG

In the declaration section near the top of the program, you will notice seed is created as a dynamic array using the descriptor “allocatable”. Its dimension is set using a “:”, which means that it is an assumed shape array – this basically means it will assume the shape of an actual parameter somewhere in the program. The subroutine random_number(r) generates a pseudorandom number from the uniform distribution over the range 0 < r < 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s