Random 读取和打印随机数

Random 读取和打印随机数,random,fortran,fortran90,Random,Fortran,Fortran90,我有下面的程序和下面的程序输入数据文件,其中包含10行不同的数据。我想随机读取这些数据,而不是按顺序,例如,它可能会读取第3行,然后可能读取第5行,不像数字1 2 3 4。。。然后我想随机打印这些数字 program rand implicit none integer::i, ok real(kind=8) , allocatable , dimension(:):: s integer, parameter:: nstep = 1, natom = 10 integer

我有下面的程序和下面的程序输入数据文件,其中包含10行不同的数据。我想随机读取这些数据,而不是按顺序,例如,它可能会读取第3行,然后可能读取第5行,不像数字1 2 3 4。。。然后我想随机打印这些数字

 program rand
  implicit none
  integer::i, ok
  real(kind=8) , allocatable , dimension(:):: s
  integer, parameter:: nstep = 1, natom = 10
  integer:: seed, rand


  open(unit=2,file="fort.2",status="old",action="read")


  allocate(s(natom),stat=ok)
  if(ok/=0)then
  print*,"problem allocating position array"
  end if

  do i=1,natom
  read(2,*)s(i)
  print*,i=(rand(seed))
  end do
  end program rand
输入文件:

   1.004624
   1.008447
   1.028897
   1.001287
  0.9994195
   1.036111
  0.9829285
   1.029622
   1.005867
  0.9372157

一般算法看起来

  • 行[N]
  • 创建一个数组
    索引[N]={1,2,…N}
  • 使用简单的洗牌算法洗牌
    索引
    数组
  • 为每个
    i
    遍历
    索引[i]
    ,直到
    size
    并输出
    行[i]

  • 您必须自己将其转换为您的语言

    正如@IanBush在评论中以及@Sazzad在其回答中所建议的那样,一种合理的方法是将整个文件读入一个数组,就像您的程序已经在做的那样。然而,在我看来,简单的吹嘘并不会导致随机打印。这只是一个新订单。这就是我提出这一解决办法的原因。 “随机”意味着,如果打印数量有限,则可以多次打印相同的号码,而其他号码则根本不打印。正如我所看到的,你的问题是如何随机选择。由于您付出了一些努力,下面是您的程序的修改版本

    program rand
        implicit none
        integer::i, ok, idx
        real(kind=8) , allocatable , dimension(:):: s
        integer, parameter:: nstep = 1, natom = 10
        integer:: seed!, rand
        real(kind = 8) :: randNum
        !
        !
        open(unit=2,file="fort.2",status="old",action="read")
        !
        !
        allocate(s(natom),stat=ok)
        if(ok/=0)then
            print*,"problem allocating position array"
        end if
        !
        do i=1,natom
            read(2,*)s(i)
            !print*,i=(rand(seed))
        end do
        !
        CALL random_seed() ! Initialize a pseudo-random number sequence
        ! to the default state. For serious program, do not use the default
        ! use for example the program on the website of gnu fortran
        ! https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html
        !
        do i=1,natom !you can and should change natom here to something else
            CALL random_number(randNum)
            idx = int(randNum*natom) + 1
            print*,'element at ',idx,': ', s(idx)
        end do
    end program rand
    
    这一区别在于打印是在原始程序中注释的,并且有一个新的循环可以随机打印。您将看到一些数字将被多次打印。为了给每个数字一个打印的机会,您应该在打印循环中设置大量的迭代次数。
    在这个答案中,我使用了随机数的默认种子,这不是一个好主意。在gnufortran()的网站上,您可以找到初始化随机种子的好方法。如果不考虑再现性,这是一个好的编程习惯。

    为什么要这样做?例如,根据您想要的内容,读取整个文件,然后洗牌数组,最后打印出您想要的内容可能会更简单;如果可能的话,最好先阅读所有数据。下面的答案有助于解决您的问题吗?如果它有帮助,请接受它来帮助那些有类似问题的人。如果没有帮助,请让我知道,这样我可以删除我的,以节省人们浪费时间看它。