如何在[0,5]范围内在fortran 90中生成整数随机数? [英] how to generate integer random number in fortran 90 in the range [0,5]?

查看:23
本文介绍了如何在[0,5]范围内在fortran 90中生成整数随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Fortran 编程的新手.任何人都可以帮我解决这个问题.我在生成整数随机数时遇到问题在 [0,5] 范围内 fortran 随机数使用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 number in the range [0,5] in fortran random number using random_seed and rand

推荐答案

为了支持 Alexander Vogt 的 answer,我将概括.

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中生成整数随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆