Generating random values from 0 to 100

I need to generate value from one threshold to another, but random_number() only provides me with an “uncontrollable” random, so to speak. How to direct randomness?

From

You can transform the uniform random sample from random_number() to random integers in range [n,m] by

call random_number(u)
j = n + FLOOR((m+1-n)*u)  ! We want to choose one from m-n+1 integers

So, for [0,100] you can do

call random_number(u)
j = FLOOR(101*u) 
1 Like

Are you asking for random integers in the [0,100] range, or random floating point numbers?

OP perhaps is asking how to generate repeatable random number.
See below, you need to set the seed of the random number generator.

https://masuday.github.io/fortran_tutorial/random.html

It says,

Seeding a random number

Given a definite environment, random_number generates a defined sequence of random numbers. The subroutine keeps an internal state, which is the source of random numbers. Once you call random_number, it changes the internal state and generates a new random number. It means, when you start from a particular state, you should get the same sequence of random numbers. This reproducibility is useful to reproduce the same results in simulation.

The seed is integer numbers that define the initial state. The seed size depends on random number generators, and each compiler implements a different generator in random_number. It means that some compilers define it as an integer vector with 2 elements, but some may use a vector with 4 elements. So, in Fortran, a subroutine (random_seed) tells you how many integers are needed in the seed vector. Also, this subroutine puts a new seed and returns the current seed.

Here is the following syntax to inquire the number of elements in a seed vector. You need a variable to receive the number.

integer :: n

call random_seed(size=n)

An idiom to prepare the seed is to allocate a seed vector and to put arbitrary values to the vector. The following code puts the seed.

integer :: n
integer,allocatable :: seed(:)

call random_seed(size=n)
allocate(seed(n))
seed = 123456789    ! putting arbitrary seed to all elements
call random_seed(put=seed)
deallocate(seed)

If you want to know the current seed, option get= is useful.

integer :: n
integer,allocatable :: seed(:)

call random_seed(size=n)
allocate(seed(n))
call random_seed(get=seed)
print *,seed
dealloocate(seed)

You can also see below,

2 Likes