init_random_seed_by_dat Subroutine

public subroutine init_random_seed_by_dat()

NAME

init_random_seed_by_dat(3f) - [M_random] seed random_number(3f) with values from date_and_time(3f)
(LICENSE:MIT)

SYNOPSIS

subroutine init_random_seed_by_dat()

DESCRIPTION

A simple wrapper around random_seed(3f) that uses the date_and_time(3f)
intrinsic to initialize the seed so you can easily call
random_number(3f) with varying pseudo-random real number sequences

EXAMPLE

Sample program:

 program demo_init_random_seed_by_dat
 use M_random, only : init_random_seed_by_dat
 integer :: i
 real    :: x
    call init_random_seed_by_dat()
    do i=1,10
       ! generate real pseudo-random numbers from 0 to <1.0
       call random_number(x)
       write(*,*)i,x
    enddo
 end program demo_init_random_seed_by_dat

Results

  >     1  0.644704163
  >     2  0.244343698
  >     3  0.516471267
  >     4  0.296542704
  >     5  0.681771278
  >     6  0.449223280
  >     7  0.915870190
  >     8  0.466257989
  >     9  0.912388682
  >    10  0.597788215

AUTHOR

John S. Urban

LICENSE

MIT License

Arguments

None

Source Code

subroutine init_random_seed_by_dat()

! ident_6="@(#) M_random init_random_seed_by_dat(3f) initialize random_number(3f) to return a single value using date_and_time(3f)"

! Initially based on a post on comp.lang.fortran.
  integer :: ival(8)
  integer :: n, v(3), i
  integer, allocatable :: seed(:)
  call date_and_time(values=ival)
  v(1) = ival(8) + 2048*ival(7)
  v(2) = ival(6) + 64*ival(5)                     ! skip value(4) because it is the timezone, which is typically constant
  v(3) = ival(3) + 32*ival(2) + 32*8*ival(1)
  call random_seed(size=n)
  if(allocated(seed))deallocate(seed)
  allocate(seed(n))
  call random_seed()                              ! give the seed an implementation-dependent kick
  call random_seed(get=seed)
  do i=1, n
     seed(i) = seed(i) + v(mod(i-1, 3) + 1)
  enddo
  call random_seed(put=seed)
  deallocate(seed)
end subroutine init_random_seed_by_dat