Fortran Coder

查看: 11225|回复: 7
打印 上一主题 下一主题

[求助] random_numer( )不随机问题

[复制链接]

954

帖子

0

主题

0

精华

大师

F 币
184 元
贡献
75 点

规矩勋章元老勋章新人勋章水王勋章热心勋章

QQ
楼主
发表于 2014-12-5 21:38:16 | 显示全部楼层
不知道你用的什么编译器?

如果是 gfortran 的话,你需要自己根据系统时间生成种子。Linux 下还可以访问 /dev/urandom 获取种子

[Fortran] 纯文本查看 复制代码
  program main
  implicit none
   interface
	subroutine random_arr(a)
	implicit none
	integer(4),intent(out),allocatable ::a(:)
	end
   end interface
   integer , allocatable :: A(:)
   integer , allocatable :: B(:)
   integer len
call init_random_seed()
call random_arr(A)
call random_arr(B)
print *,A
print *,B

  end program
  
subroutine random_arr(a)
implicit none
real(4) temp,temp2
integer(4) siz,i
integer(4),intent(out),allocatable ::a(:)

call random_number(temp)
print *,temp
siz=int(temp*20)
print *," ",siz," "
allocate (a(siz))
a(:)=0
loop:do i=1,siz
30 call random_number(temp2)
 a(i) = int(temp2*20)
if(i/=1)then
if(all( a(1:(i-1))/=a(i)) )then
cycle loop
else 
goto 30
end if
end if
End do loop
end subroutine

subroutine init_random_seed()
  use iso_fortran_env, only: int64
  implicit none
  integer, allocatable :: seed(:)
  integer :: i, n, un, istat, dt(8), pid , lcg
  integer(int64) :: t

  call random_seed(size = n)
  allocate(seed(n))
  call system_clock(t)
  if (t == 0) then
     call date_and_time(values=dt)
     t = (dt(1) - 1970) * 365_int64 * 24 * 60 * 60 * 1000 &
          + dt(2) * 31_int64 * 24 * 60 * 60 * 1000 &
          + dt(3) * 24_int64 * 60 * 60 * 1000 &
          + dt(5) * 60 * 60 * 1000 &
          + dt(6) * 60 * 1000 + dt(7) * 1000 &
          + dt(8)
  end if
  pid = getpid()
  t = ieor(t, int(pid, kind(t)))
  do i = 1, n
     seed(i) = lcg(t)
  end do
  call random_seed(put=seed)
end subroutine init_random_seed

function lcg(s)
  use iso_fortran_env, only: int64    
  integer :: lcg
  integer(int64) :: s
  if (s == 0) then
     s = 104729
  else
     s = mod(s, 4294967296_int64)
  end if
  s = mod(s * 279470273_int64, 4294967291_int64)
  lcg = int(mod(s, int(huge(0), int64)), kind(0))
end function lcg
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2024-5-19 09:45

Powered by Tencent X3.4

© 2013-2024 Tencent

快速回复 返回顶部 返回列表