【问题标题】:gfortran and random numbersgfortran 和随机数
【发布时间】:2014-02-10 21:35:26
【问题描述】:

我正在尝试使用来自 mac-ports (OS-X) 的 Gfortran 4.7 编译以下简单代码:

program main

implicit none

integer :: n = 1, clock, i

integer, dimension(1) :: iseed

! initialize the random number generator
call random_seed(size = n)

call system_clock(COUNT=clock)

iseed = clock + 37 * (/ (i - 1, i = 1, n) /)
! iseed = clock
! iseed = abs( mod((clock*181)*((1-83)*359), 104729) )
call random_seed(PUT = iseed)

end program main

并出现此错误:

gfortran-mp-4.7  tmp.f90
tmp.f90:17.23:

call random_seed(PUT = iseed)
                   1
Error: Size of 'put' argument of 'random_seed' intrinsic at (1) too small (1/12)

我根本不使用 Fortran(我是 C++ 人),所以如果有人能提供帮助并使其正常工作,我将不胜感激。

附言在一个类似的问题上,我发现了几个论坛帖子,当前取消注释的解决方案类似于this GCC bug report 中提到的解决方案。

提到abs 的那个in this stack overflow post(添加它时没有PID,因为无论如何我都不并行运行。

更新:

以下作品:

program main

implicit none

integer :: n = 12, clock, i

integer, dimension(:), allocatable :: iseed

! initialize the random number generator
allocate(iseed(n))
call random_seed(size = n)

call system_clock(COUNT=clock)

iseed = clock + 37 * [(i, i = 0,n-1)]
call random_seed(PUT = iseed)

end program main

【问题讨论】:

  • 您链接到的 GCC 错误报告有解决方案:您需要设置 n = 12 和 integer, dimension(12) :: iseed。 random_seed 的 put 参数需要一个由 12 个整数组成的数组。

标签: random fortran gfortran


【解决方案1】:

为了放大@Yossarian 的评论,这个

call random_seed(size = n)

在n 中返回要初始化RNG 时必须使用的秩1 整数数组的大小。我建议通过将 iseed 的声明更改为:

integer, dimension(:), allocatable :: iseed

然后,在获得n 的值后,分配它:

allocate(iseed(n))

用你喜欢的值填充它,然后put 它。

您也许可以在这样的一个语句中分配和填充它:

allocate(iseed(n), source = clock + 37 * [(i, i = 0,n-1)])

我写可能,因为这取决于你的编译器的最新程度。

编辑,在 OP 评论之后

不,你还没有完全理解我的建议。

通过执行获取n的值

call random_seed(size = n)

不要将 n 初始化为 12。

然后在一个语句(使用源分配)或allocate 语句后跟一个赋值语句中分配数组并填充它。

在

allocate(iseed(n))
call random_seed(size = n)

操作顺序不正确。这将iseed 设置为12 个元素(这是执行第一条语句时n 的值),然后将n 设置为RNG 所需的数组大小。只要那是 12,您就不会看到任何问题,但是一旦您将代码移植到另一个编译器,甚至可能是同一编译器的另一个版本,您就有可能遇到需要不同大小的整数数组的 RNG .无需将值硬连线到您的代码中,所以不要。

【讨论】:

  • 感谢您的回复。我放了更新代码,是你的意思吗?我确实编译得很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多