FORTRAN中用于产生随机数的子程序有random_seed和random_number,其中random_seed产生seed,random_number根据seed的值产生随机数。当random_seed()的参数为空时,其会给出一个默认的seed值,这意味着每次调用时产生的随机数都是相同的。(这也是有用的,这意味着你每次在执行程序的时候,会得到相同随机数序列,这些便于调试,可是有时候可能会须要每次生成不一样的随机数序列以知足程序的要求)。
html
下面的方法利用系统时间产生随机数:shell
subroutine init_random_seed() integer :: i,n,clock integer,dimension(:),allocatable :: seed call random_seed(size=n) allocate(seed(n)) call system_clock(count=clock) seed=clock+37*(/(i-1,i=1,n)/) call random_seed(PUT=seed) deallocate(seed) end subroutine
该子程序来源于GNU Fortran:http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.htmldom
(以上内容转载自:http://blog.sina.com.cn/s/blog_872ecf9f01010kwl.html)spa
调用经过以下程序可进行调用:调试
program randomnum implicit real*8(a-h,o-z) call init_random_seed() call random_number(x) write(*,*)x end
注意:在一个程序中只需调用一次子程序 init_random_seed(),特别是在有另外一个子程序也须要产生随机数的状况下,仍无需(说是不能或许更为恰当些)再次调用init_random_seed()。不然,若两次调用时间相差很小,可能出现生成的随机数的seed同样的状况,此时就会出现某个随机数连续出现若干次的状况。code