How can i generate random numbers in a specific interval such as [0, 100] in fortran?
I wan to generate and assign them to an array.
CALL RANDOM_NUMBER(my_array) will do the job, but in the 0<=r<1 range. Note that
my_array should of course be
my_array = 100*my_array will be in the 0<=r<100 range. If you want integers including 100, then multiply by 101 and take the integer part!
You may also want to change the seed each time you launch your program:
There is also a Fortran 2018 function, but I have never used it:
Because of course these numbers are not random! They are pseudo-random numbers, generally generated by a mathematical sequence. If you don’t change the seed, the sequence will be the same each time you run your program: but this can be interesting if you modify something in your program and want to test if it still gives exactly the same result.
random_number returns samples from a uniform distribution. Here’s a “naive” implementation of random sampling from a normal distribution:
I say “naive” because it appears to work but statistics are not my strong suit.
See also our open issue #135 in stdlib for implementing random number generators from various distributions such as uniform, normal or gamma.
I’ve got a few super simple examples in my testing framework you could take a look at. I haven’t looked at them at all from a statistical standpoint so I have no idea what the distributions are. They’ll be approximately whatever the underlying random number generator uses I guess. But if you just need something quick and dirty it’s a decent starting point.