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?
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
Pseudorandom Number Generation. Software-generated random numbers only are pseudorandom. They are not truly random because the computer uses an algorithm based on a distribution, and are not secure because they rely on deterministic, predictable algorithms.
random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.
A pseudorandom number generator's number sequence is completely determined by the seed: thus, if a pseudorandom number generator is reinitialized with the same seed, it will produce the same sequence of numbers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With