问题
Here's a simple fortran program I was using to understand the behavior of the fortran intrinsic uniform random number generator.
program test_prog
implicit none
integer, allocatable :: seed(:)
real(8), dimension(2) :: unif_rand
integer :: nseed ! minimum number of random seed value
integer :: i,n
call random_seed( size=nseed )
nseed = 100
allocate( seed(nseed) )
write(*,*) "nseed: ",nseed
do n = 1,5
seed(:) = n**10
call random_seed( put=seed )
call random_number(harvest=unif_rand)
write(*,1000) seed(nseed),unif_rand(1),unif_rand(2)
write(*,*) ""
1000 format(i12," ",f12.8," ",f12.8)
enddo
end program test_prog
When I compile with gfortran I get sensible results:
1 0.76322100 0.72975598
1024 0.30901699 0.80380552
59049 0.05916934 0.69849271
1048576 0.59972035 0.71558547
9765625 0.79167428 0.37621382
But when I compile with pgf90 I get very different results:
1 0.00000024 0.00000024
1024 0.00024414 0.00024414
59049 0.01407838 0.01407838
1048576 0.25000003 0.25000003
9765625 0.32830648 0.32830648
With small seed values the PGI results are always very close to zero, so it seems the PGI compiler does something to make the random values such that they are scaled by the seed value. This is very problematic for my current project because I need it to give consistent results for different compilers.
Some google searches haven't turned up any explanation, so I'm wondering if anyone here can explain why these results are so different?
Or does anyone know of a trick to make the PGI compiler results more in line with the GNU compiler results?
Or does anyone know of some code for a decent random number generator available online that I could implement as an alternative to the intrinsic routines?
回答1:
Firstly, as discussed here several times before, the Fortran standard gives NO requirement or guarantee about the quality of the intrinsic random number generator. One has to use external libraries to have any quality guarantee.
Secondly, the seed
in a PRNG is there to give the source of initial entropy. Different generators are able to cope with different seeds with various success but in poor generators you need the bits in the seed to also to be distributed relatively "randomly". Too much coherence of the seed bits and the results may be terrible.
As to which external library to use - recommendations are off topic, but there are plenty of them and you will even find articles with comparisons of the quality of individual methods. Many recommendations were already given on this very site in the comments or answers under similar questions. Just search for random and fortran.
来源:https://stackoverflow.com/questions/49163403/random-number-gives-vastly-different-behavior-between-gnu-and-pgi-fortran-comp