Fortran 中的随机数

Random Number in Fortran

我正在学习Fortran,我想做一个小游戏来练习输入法。 objective是找好号,谁是随机的。我编写了一个代码来生成数字,但我的问题是,结果是一个随机数,但它总是一样的。 例如,当我执行代码 3 次时,它打印了 21 3 次。

这是我的代码:

program find_good_number
    integer :: random_number
    integer :: seed
    seed = 123456789
    call srand(seed)
    random_number = int(rand(0)*100)
    print*, random_number
end program find_good_number

你能帮帮我吗? 谢谢

使用带有标准内在函数的 GNU Fortran 10.3,并要求 Fortran 运行时库查看种子,似乎程序的每次调用都会产生不同的随机数系列。所以这对于您想要的那种应用程序来说是可以的。

使用此代码:

Program TestRandom1

  implicit none

  integer :: randomSeedSize
  integer :: count = 3
  integer :: k     = 0
  real    :: rx    = 0.0

  call random_seed(size = randomSeedSize)
  write (*,'(a,i4)')   'size of random seed (in integers): ',  &
                       randomSeedSize

  call random_seed()  ! use system-provided seed

  do k = 1, count
      call random_number(rx)
      write (*, '(a,f10.8)') 'rx = ', rx
  end do

End Program TestRandom1

上下文:

$ 
$ uname -s -m -r
Linux 5.13.9-100.fc33.x86_64 x86_64
$ 
$ gfortran --version
GNU Fortran (GCC) 10.3.1 20210422 (Red Hat 10.3.1-1)
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ 

测试:

$ 
$ random1.x
size of random seed (in integers):    8
rx = 0.23642105
rx = 0.39820033
rx = 0.62709534
$ 
$ random1.x
size of random seed (in integers):    8
rx = 0.84118658
rx = 0.45977014
rx = 0.09513164
$ 
$ random1.x
size of random seed (in integers):    8
rx = 0.33584720
rx = 0.86550051
rx = 0.26546007
$ 

8*32 = 256 位的种子大小看起来与提到的 xoshiro256 算法一致 here in the GNU Fortran documentation.