问题描述
我是 Fortran 编程的新手.谁能帮我解决一下.我遇到了生成整数随机数的问题在 fortran 随机数的 [0,5] 范围内使用random_seed 和 rand
I am kind of new in the fortran proramming.Can anyone please help me out with the solution.i am having a problem of generating integer random numberin the range [0,5] in fortran random number usingrandom_seed and rand
推荐答案
为了支持 Alexander Vogt 的答案,我'将概括.
To support the answer by Alexander Vogt, I'll generalize.
内在 random_number(u)
从区间 [0,1) 上的均匀分布返回实数 u
(或此类数组).【即包含0但不包含1】
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.]
为了对整数 {n, n+1, ..., m-1, m} 进行离散均匀分布,将连续分布划分为 m+1-n 个大小相等的块,将每个块映射到一个整数.一种方法可能是:
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
如您所见,对于 {0, 1, 2, 3, 4, 5} 的初始问题,这简化为
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
对于您评论中的另一种情况 {-1, 0, 1}
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.
这篇关于如何在[0,5]范围内的fortran 90中生成整数随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!