Why are my random numbers always the same?

后端 未结 2 1883
一生所求
一生所求 2020-11-27 08:32

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

相关标签:
2条回答
  • 2020-11-27 08:44

    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.

    0 讨论(0)
  • 2020-11-27 08:49

    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, Fortran 2018 introduced the standard an intrinsic procedure random_init. This handles both cases of selecting repeatability across invocations and distinctness over (coarray) images.

    0 讨论(0)
提交回复
热议问题