Loops 在Fortran中如何将随机数放入循环

Loops 在Fortran中如何将随机数放入循环,loops,random,fortran,Loops,Random,Fortran,我有以下代码: 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 in

我有以下代码:

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)

但是我似乎不知道如何组合代码将随机数向量输入到循环中。

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
[-100100]中的随机指数:
-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

您是在寻找增量为0.1的随机值,还是想要“连续”浮点值?(害怕引用,因为,是的,它在计算机上的精度是有限的。)你希望你的随机数看起来像什么?统一、所有整数的随机排列、有/无重复的随机选择,等等?为什么类型转换为
real(上界-下界,kind=RK)
需要?值得注意的是
nint
是统一分布的。@jack谢谢你的注释,我已经删除了它。@francescalus谢谢你的注释。但是使用
下限
不会导致从
下限
到并包括
上限
的闭合间隔。我认为这是离散的统一数的共同定义:是的,如果使用<代码> NITC,那么下和上数比中间数有一半的被抽样概率。[0,0.5)映射到0,[0.5,1.5)映射到1,[n-0.5,n)映射到n。