-1

This is a follow up to this question.

I find that Random_number() is not reliable for parallel programming, it gives non reproducible results, and my program heavily relies on random numbers.

How can I write a random number generator in Fortran that is parallel safe?

Or where can I find it?

mattiav27
  • 655
  • 2
  • 9
  • 27
  • 1
    Rather than engage in some tricky coding (which you don't know how to do yet) first convince yourself that you **must** take that approach. Don't reject out of hand the approach of using a sequential PRNG to generate all the random numbers you need and putting them somewhere (perhaps in a shared memory array) your separate processes/threads can read their own chunks. Reject this only after you have programmed it up and determined that it is a bottleneck in performance. – High Performance Mark Feb 07 '20 at 13:16
  • @HighPerformanceMark How do I tell the compiler to divide the array of random numbers in chunks and give one to each thread? – mattiav27 Feb 07 '20 at 13:58
  • 1
    A lot of information is missing here. What compiler and operating system? How are you seeding the PRNG? Are you certain that the non-reproducible results you observe are not a manifestation of a problem with with code? – evets Feb 07 '20 at 15:35
  • If you are programming shared memory you get the master thread to populate an array of `n*10^m` random numbers, where `n` is the number of threads you are using and `m` is a value appropriate to your calculation, then as the computation proceeds each of the `n` threads reads from its own chunk of the shared array. – High Performance Mark Feb 07 '20 at 15:40
  • 2
    If you are using gfortran, the manual tells you how to use random_number with multiple threads: https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fNUMBER.html. Also see https://stackoverflow.com/questions/3158213/thread-safe-mersenne-twister – M. S. B. Feb 07 '20 at 16:03

1 Answers1

2

Since Fortran 2018 it is possible to initialise the pseudo-random number generator of the invoking image so that the pseudo-random number sequence will differ from that of other images that execute a similar statement, and will be different on subsequent execution of the program.

CALL RANDOM_INIT (REPEATABLE=.FALSE., IMAGE_DISTINCT=.TRUE.) 

More info in the Fortran 2018 Standard, Section 16.9.155

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • 4
    While true, I think a multiple-image program is probably well beyond the level of experience of the person asking this question, compared with a threading model like OpenMP. – francescalus Feb 07 '20 at 16:48