random_int Function

public function random_int(first, last) result(rand_int)

NAME

random_int(3f) - [M_random] return an integer between low and high value inclusive
(LICENSE:MIT)

SYNOPSIS

function random_int(first,last) result(rand_int)

integer,intent(in) :: first,last
integer            :: rand_int

DESCRIPTION

Return an integer uniformly distributed from the set {first,,first+1,...,last-1,last}.

OPTIONS

first       lowest value of range of integer values to randomly return
last        highest value of range of integer values to randomly return

RETURNS

rand_int    a random integer value between FIRST LAST inclusive

EXAMPLE

Sample program

program demo_random_int
use M_random, only : random_int, init_random_seed_by_system_clock
implicit none
integer :: i
call init_random_seed_by_system_clock()
write(*,'(*(i0:,1x))')(random_int(1,10),i=1,20)
write(*,'(*(i0:,1x))')(random_int(-5,5),i=1,20)
end program demo_random_int

Sample output

1 3  8 1 2  6  8 7  4  10  7  3  8  3  10 1  5  2 9  8
4 5 -3 5 2 -5 -4 4 -5  -3 -2 -2 -2 -1  -2 4 -2 -2 4 -4

AUTHOR

John S. Urban

LICENSE

MIT License

Arguments

Type IntentOptional Attributes Name
integer, intent(in) :: first
integer, intent(in) :: last

Return Value integer


Source Code

function random_int(first,last) result(rand_int)
use,intrinsic :: iso_fortran_env, only : dp=>real64
implicit none
integer,intent(in)   :: first,last ! lowest and highest integer in range of integers to get
integer, allocatable :: seed(:)
integer              :: n
integer              :: rand_int
real(kind=dp)        :: rand_val
logical,save         :: called=.false.
   if(.not.called)then
   ! initialize seed
      call random_seed(size = n)
      if(allocated(seed))deallocate(seed)
      allocate(seed(n))
      call random_seed(get=seed)
      called=.true.
   endif

   ! To have a discrete uniform distribution on the integers {first, first+1,
   ! ..., last-1, last} carve the continuous distribution up into last+1-first
   ! equal sized chunks, mapping each chunk to an integer. One way is:
   !
   ! get real number from 0 up to but not including 1 (ie. [0,1)).
   call random_number(rand_val)
   ! use random value to choose an integer from first to last
   rand_int = first + floor((last-first+1)*rand_val)
   if(allocated(seed))deallocate(seed)
end function random_int