问题
I have the following small piece of code:
REAL(8) :: x
INTEGER :: i
call system_clock(i)
WRITE(*,*) 'cpu time', i
CALL random_seed(i)
CALL random_number(x)
WRITE(*,*) 'uniform RandVar', x
CPU time is working fine, but every time I run this I get the same uniform RandVar number = 0.99755959009261719, almost like random_number is using the same default seed over and over again and ignoring random seed.
What am I doing wrong?
回答1:
The same seed may well be being used: that is processor-dependent. The reason for this is that your call to random_seed is not setting the seed.
With the reference
CALL random_seed(i)
the argument i is not the (intent(in)) seed, but is the (intent(out)) size of the seed used by the processor. This call is like
CALL random_seed(SIZE=i) ! SIZE is the first dummy argument
To set the seed you need to explicitly associate with the PUT dummy argument: call random_seed(put=seed). Here the seed is a rank 1 array of size at least n where n - again processor-dependent - is the size given by call random_seed(size=n). From your call i holds this value.
Full details are given in 13.7.136 of F2008.
A common way to seed the generator is:
integer, allocatable :: seed(:)
integer size
call random_seed(size=size)
allocate(seed(size))
! set seed(:) somehow
call random_seed(put=seed)
Setting seed appropriately is not a simple process. I don't address how to do that here, but detail can be found in answers to this other question.
Use of srand(), which is mentioned in the comments, is non-standard.
来源:https://stackoverflow.com/questions/21352202/random-numbers-keep-coming-out-the-same-despite-random-seed-being-used