【问题标题】:How to Put Random Numbers into Loop in Fortran [duplicate]如何在 Fortran 中将随机数放入循环 [重复]
【发布时间】:2021-07-13 23:36:32
【问题描述】:

我有以下代码:

program outputdata   
implicit none

  real, dimension(100) :: x, y  
  real, dimension(100) :: p, q
  integer :: i  

  ! data  
  do i=1,100  
      x(i) = i * 0.1 
      y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
  end do  

  ! output data into a file 
  open(1, file = 'data1.dat', status = 'new')  
  do i=1,100  
      write(1,*) x(i), y(i)   
  end do  

  close(1) 

end program outputdata

我想编写一个非常相似的代码,但它使用一串随机数而不是顺序的 1-100。我找到了这些用于生成随机数序列的代码:

real :: r(5)

call random_seed()
call random_number(r)

但我似乎无法弄清楚如何组合代码以将随机数向量输入到循环中。

【问题讨论】:

  • 您是在寻找增量为 0.1 的随机值,还是想要“连续”的浮点值? (吓人的引号,是的,它在计算机上的精度是有限的。)
  • 你希望你的随机数是什么样的?所有整数的统一、随机排列、有/无重复的随机选择等?

标签: loops random fortran


【解决方案1】:

Fortran 没有内在的整数随机数生成器。但是写一个很容易:

module random_mod

    implicit none

contains

    function getRandInt(lowerBound,upperBound) result(randInt)
        use iso_fortran_env, only: RK => real64
        implicit none
        integer, intent(in) :: lowerBound,upperBound
        real(RK)            :: dummy
        integer             :: randInt
        call random_number(dummy)
        randInt = lowerBound + floor(dummy*(upperBound-lowerBound+1))
    end function getRandInt

end module random_mod

program random_prog
    
    use random_mod, only: getRandInt
    implicit none
    
    integer, parameter :: NSIM = 100
    integer :: i, Index(NSIM)
    
    do i = 1, NSIM
        Index(i) = getRandInt(-NSIM,NSIM)
    end do
    
    write(*,"(*(g0,:,' '))") "Random Indices in [",-NSIM,",",NSIM,"] :"
    write(*,"(10(g0,:,' '))") Index 

end program random_prog

以上代码产生:

$gfortran -std=gnu *.f90 -o main
$main
Random Indices in [ -100 , 100 ] :
-97 -37 35 86 -91 27 -33 60 -58 -70 
61 22 -70 40 43 29 9 -37 74 -21 
39 -19 96 -31 -46 41 24 0 59 -4 
-83 -54 96 9 -80 -44 44 -4 25 45 
15 -83 -45 -49 -95 -47 25 -95 84 79 
81 -42 -6 -40 95 -63 66 47 -77 51 
13 -17 73 -48 -80 23 -75 79 -33 -79 
69 -52 61 -31 -95 -4 79 85 81 87 
-16 87 -14 -43 -25 56 65 -33 -99 83 
84 -36 26 20 -22 -99 33 -95 -48 75

在您的代码中,您需要做的就是将索引i 替换为函数调用getRandInt(lowerBound = 1, upperBound = 100) 以获得随机索引而不是i

【讨论】:

  • 为什么需要类型转换real(upperBound-lowerBound,kind=RK)
  • 值得注意的是nintdoes not lend itself要均匀分布。
  • @jack 感谢您的留言,我已将其删除。
  • @francescalus 感谢您的来信。但是使用floor 不会导致从lowerBound 到并包括upperBound 的封闭区间。我认为这是离散统一数的通用定义:en.wikipedia.org/wiki/Discrete_uniform_distribution
  • 是的,如果使用nint,那么较低和较高的数字被采样的概率是中间数字的一半。 [0,0.5) 映射到 0,[0.5,1.5) 映射到 1,... [n-0.5, n) 映射到 n。
猜你喜欢
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多