【问题标题】:How to write a function that uses 2 values of another function which generates 10000 values?如何编写一个使用另一个函数的 2 个值生成 10000 个值的函数?
【发布时间】:2017-10-14 21:01:17
【问题描述】:

我编写了一个线性同余生成器,可以将 10000 个伪随机值打印到终端。这是模块的一部分,因此是它自己的功能。我现在想编写一个新函数,它接受 2 个随机均匀分布的数字,并在 box muller 方法中使用它们来生成另外 2 个数字。我了解 box muller 部分本身,我只是不明白我如何对其进行编程以仅从之前的 10000 中获取 2 个值?这是我的代码:

module rng
  implicit none

  integer, parameter :: dp = selected_real_kind(15,300)
  real(kind=dp) :: A=100, B= 104001, M = 714025 

contains 

function lcg(seed)
  integer :: lcg
  integer, optional, intent(in) :: seed
  real(kind=dp) :: x = 0

  if(present(seed)) x = seed
  x = mod(A * x + B, M)
  lcg = x
end function

end module


program lcgtest
  use rng
  implicit none
  integer :: N


  do N = 1, 10000
    print *, lcg()
  end do
end program 

谢谢。

【问题讨论】:

  • 这是一个练习吗?因为对于实际使用,您会发现那里有很好的库。
  • "从之前的 10000 中取 2 个值"。从字面上看,您可以将 10000 个值保存在一个数组中。你用什么标准来选择这两个?你为什么要那样做?

标签: fortran gfortran fortran90


【解决方案1】:

您的函数生成 1 个整数,而不是 1000。只需调用两次,您就有两个数字。

do
  a = lcg ()
  b = lcg ()

  !do something with a and b
end do

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2012-10-28
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多