문제

I have a configuration of N particles and in a loop I want to choose each of them but without repeat. I have below codes but I just found out some repeats on it.

    do k=1,num
       u=mod(16807.d0*u,2147483647.d0)
       v=u/2147883648.d0
       s=int(dble(num)*v)+1
       if (s.gt.num) s=1
    end do
도움이 되었습니까?

해결책

I'm not entirely sure I understand what you mean, and the code is a bit too long for a comment, but do you mean something like the following?

ian@ian-pc:~/test/stackoverflow$ cat shuffle.f90
Program shuffle

  Implicit None

  Integer, Parameter :: n = 10

  Integer, Dimension( 1:n ) :: choices

  Real :: a

  Integer :: n_chosen
  Integer :: this
  Integer :: tmp
  Integer :: i

  choices = (/ ( i, i = 1, n ) /)

  n_chosen = 0
  Do i = 1, n
     Call random_number( a )
     this = a * ( n - n_chosen ) + 1
     Write( *, * ) 'Chosen ', choices( this )
     tmp = choices( this )
     choices( this ) = choices( n - n_chosen )
     choices( n - n_chosen ) = tmp
     n_chosen = n_chosen + 1
  End Do

End Program shuffle
ian@ian-pc:~/test/stackoverflow$ nagfor shuffle.f90
NAG Fortran Compiler Release 5.3.1(907)
[NAG Fortran Compiler normal termination]
ian@ian-pc:~/test/stackoverflow$ ./a.out
 Chosen  5
 Chosen  10
 Chosen  4
 Chosen  9
 Chosen  8
 Chosen  2
 Chosen  6
 Chosen  3
 Chosen  1
 Chosen  7
ian@ian-pc:~/test/stackoverflow$ ./a.out
 Chosen  6
 Chosen  3
 Chosen  5
 Chosen  4
 Chosen  9
 Chosen  8
 Chosen  10
 Chosen  2
 Chosen  7
 Chosen  1
ian@ian-pc:~/test/stackoverflow$ 

다른 팁

I modified your code and I used it in my program. it works but the problem is I did it in a time interval between 0 and t and every time it makes a same number order :D but the good point is without any repeats in each one.

  Program shuffle
  Implicit None
  Integer, Parameter :: num = 27
  Integer, Dimension( 1:num ) :: jj
  Real*8 uni,ir
  Integer :: n_chosen
  Integer :: this
  Integer :: tmp
  Integer :: i,ii
  jj = (/ ( i, i = 1, num ) /)
  ir=1245.d0
  n_chosen = 0
  Do i = 1, num
   Call ran(ir,uni)
   this = uni * ( num - n_chosen ) + 1
   ii=jj(this)
   tmp = jj( this )
   jj( this ) = jj( num - n_chosen )
   jj( num - n_chosen ) = tmp
   n_chosen = n_chosen + 1
  End Do
  end program
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top