我有一个N
粒子的配置,在一个循环中,我想选择每个粒子,但没有repeat
。我有below codes
但我刚刚发现了一些重复。
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
答案 0 :(得分:1)
我不完全确定我理解你的意思,而且代码对于评论来说有点太长了,但是你的意思是以下内容吗?
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$
答案 1 :(得分:0)
我修改了你的代码,我在我的程序中使用它。它可以工作,但问题是我在0到t之间的时间间隔和每次它产生相同的数字顺序时做到了:D但是好点在每一个都没有重复。
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