About the pseudo random generator in gfortran

Jerry DeLisle jvdelisle@charter.net
Fri May 20 20:12:00 GMT 2016


On 05/20/2016 08:56 AM, ch l wrote:
> Hi,
> 
> I'm a ordinary user of The GNU Fortran Compiler. I'm still trying my best
> to learn the Fortran programming language. When I am using The GNU Fortran
> Compiler, I try to use the internal pseudo random generator like this:
> 
> call random_seed()
> call random_number(rnd)
> 
> This code is quite common on many Fortran textbook or on many websites. The
> 2nd line might also be use in a DO loop. Although I compile and run it for
> many times, I get totally SAME random number(s). I have tested the same
> code on Intel 's Fortran Compiler, Intel 's Fortran Compiler will give
> different number for the every time I run it.
> 
> I have tried this both on Windows (MinGW, TDM-GCC) and directly on Linux's
> original GCC. They seem to have same problem. I also tried to search on
> Google, but there seems no useful answer.
> 
> I have read the official wiki, the example in the function RANDOM_NUMBER
> (which URL is https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fNUMBER.html
> ) use a new SUBRUTINE named init_random_seed, and its define is in the
> RANDOM_SEED page (
> https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED).
> So I have tried the init_random_seed subroutine in my own code, it seems
> works well, I get the different number for every times I run the program.
> 
> But I'm really confused that why GNU's Fortran Compiler requires a external
> subroutine to generate random number. So I wonder if this is a bug or it
> is just designed to behave like this. It will be better if you can teach me
> a lot. Maybe there is a more elegant way to generate random number. ;)
> 

This is by design. For those people who want to have repeatable results they can
use the same seed each time they run.  Remember these are pseudo-random number
generators.  If you want truly unpredictable pseudo-random number sequences you
must initialize the seed values in as random a way as possible.  The example
code in the manual does a pretty good job of this.  If you are running on a
linux based system with /dev/urandom, the linux kernal does a pretty good job of
maintaining an "entropy pool" of a mixture of various CPU states, clocks, etc.
The example code initializes the seeds using that, making the seed very
unpredictable.

Regards,

Jerry



More information about the Fortran mailing list