如何在fortran 90中生成[0,5]范围内的整数随机数? [英] how to generate integer random number in fortran 90 in the range [0,5]?
问题描述
任何人都可以请帮我解决方案。
i在使用
random_seed和rand的fortran随机数中产生整数随机数
的范围[0,5],问题是
为了支持Alexander Vogt的答案,我将推广。 / p>
内在 random_number(u)
返回一个实数 u
(或者这样的一个数组)在区间[0,1)内的均匀分布。为了在整数{n,n + 1,...,m-1上有一个离散的均匀分布,它包含0但不是1。]
,m}将连续分布分成m + 1-n个相等大小的块,将每个块映射为一个整数。一种方式可能是:
$ p $ call random_number(u)
j = n + FLOOR((m + 1-n) *你)!我们想从m-n + 1中选择一个整数
正如您所看到的,对于最初的问题对于{0,1,2,3,4,5},这减少到
调用random_number(u)
j = FLOOR(6 * u)! n = 0和m = 5
另一种情况在您的评论{-1,0, 1}
call random_number(u)
j = -1 + FLOOR(3 * u)! n = -1和m = 1
当然,连续的整数,并且应该注意数字问题。
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 number in the range [0,5] in fortran random number using random_seed and rand
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.
这篇关于如何在fortran 90中生成[0,5]范围内的整数随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!