Why are my random numbers always the same?

2019-01-08 00:58发布

问题:

I'm using the random_number subroutine from Fortran, but in different runs of program the number which is being produced doesn't change. What should I include in my code so every time I compile and run the program the numbers change?

回答1:

The random number generator produces pseudo-random numbers. To get different numbers each run, you need to intialise the random seed at the start of your program. This picks a different starting position in the pseudo-random stream.



回答2:

The sequence of pseudorandom numbers coming from call(s) to random_number depends on the algorithm used by the processor and the value of the seed.

The initial value of the seed is processor dependent. For some processors this seed value will be the same each time the program runs, and for some it will be different. The first case gives a repeatable pseudorandom sequence and the second a non-repeatable sequence.

gfortran (before version 7) falls into this first category. So, you will need to explicitly change the random seed if you wish to get non-repeatable sequences.

As stated in another answer the intrinsic random_seed can be used to set the value of the seed and restart the pseudorandom generator. Again, it is processor dependent what happens when the call is call random_seed() (that is, without a put= argument). Some processors will restart the generator with a repeatable sequence, some won't. gfortran (again, before version 7) is in the first category.

For processors where call random_seed() gives rise to a repeatable sequence an explicit run-time varying seed will be required to generate distinct sequences. An example for those older gfortran versions can be found in the documentation.

It should be noted that choosing a seed can be a complicated thing. Not only will there be portability issues, but care may be required in ensuring that the generator is not restarted in a low entropy region. For multi-image programs the user will have to work to have varying sequences across these images.

On a final note, there is a proposal in the draft Fortran 2018 standard for an intrinsic random_init. This handles both cases of selecting repeatability across invocations and distinctness over (coarray) images.