dimanche 14 août 2016

generating random numbers in Fortran

I am trying to generate a sequence of random numbers $\xi_i$ uniformly distributed in [0,1] using the built-in functions in Fortran. The sequence has to be reproducible so I want to seed the random number generator by the index $i$ (that is the position of $\xi_i$ in the sequence) rather than using the system clock for the seed. Below is my code:

module rand

contains

  function generate_random(iseed) result(xi1)
  !!
  implicit none
  integer, intent(in) :: iseed

  integer, dimension(:), allocatable :: seed
  integer :: i, j, n
  real :: xi1

  !!-generate a seed first
  call random_seed(size = n)
  allocate(seed(n))
  seed = iseed * (/(i, i=1,n,1)/)
  call random_seed(PUT = seed)
  deallocate(seed)

  call random_number(xi1)

  !!
end function generate_random

end module rand

program test

  use rand
  implicit none
  integer :: i, imax

  imax=100

  do i=1,imax
     print *, generate_random(i)
  enddo

end program test

However the result of this shown in the plot where $\xi_i$ is plotted vs. the index $i$ clearly has some pattern, so it is not so random after all. How to improve this, i.e., to make it "more random"?

enter image description here




Aucun commentaire:

Enregistrer un commentaire