how to generate integer random number in fortran 90 in the range [0,5]?

感情迁移 提交于 2019-11-30 09:18:29

What about:

program rand_test
  use,intrinsic :: ISO_Fortran_env
  real(REAL32)  :: r(5)
  integer       :: i(5)

  ! call init_random_seed() would go here

  call random_number(r)

  ! Uniform distribution requires floor: Thanks to @francescalus 
  i = floor( r*6._REAL32 )

  print *, i
end program
francescalus

To support the answer by Alexander Vogt, I'll generalize.

The intrinsic random_number(u) returns a real number u (or an array of such) from the uniform distribution over the interval [0,1). [That is, it includes 0 but not 1.]

To have a discrete uniform distribution on the integers {n, n+1, ..., m-1, m} carve the continuous distribution up into m+1-n equal sized chunks, mapping each chunk to an integer. One way could be:

call random_number(u)
j = n + FLOOR((m+1-n)*u)  ! We want to choose one from m-n+1 integers

As you can see, for the initial question for {0, 1, 2, 3, 4, 5} this reduces to

call random_number(u)
j = FLOOR(6*u)            ! n=0 and m=5

and for the other case in your comment {-1, 0, 1}

call random_number(u)
j = -1 + FLOOR(3*u)       ! n=-1 and m=1

Of course, other transformations will be required for sets of non-contiguous integers, and one should pay attention to numerical issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!