Reputation: 43
I am learning Fortran and I would like to make a little game to practice the input. The objective is to find the good number, who is a random one. I made a code to generate the number but my problem is that, the result is a random number, but it's always the same. For example, when I execute the code 3 times, it print 21 the three times.
Here is my code :
program find_good_number
integer :: random_number
integer :: seed
seed = 123456789
call srand(seed)
random_number = int(rand(0)*100)
print*, random_number
end program find_good_number
Can you help me please ? Thanks
Upvotes: 2
Views: 1641
Reputation: 4733
Using GNU Fortran 10.3 with the standard intrinsics, and asking the Fortran runtime library to peek the seed, it seems that every invocation of the program does result in a different serie of random numbers. So that would be OK for the sort of application you have in mind.
Using this code:
Program TestRandom1
implicit none
integer :: randomSeedSize
integer :: count = 3
integer :: k = 0
real :: rx = 0.0
call random_seed(size = randomSeedSize)
write (*,'(a,i4)') 'size of random seed (in integers): ', &
randomSeedSize
call random_seed() ! use system-provided seed
do k = 1, count
call random_number(rx)
write (*, '(a,f10.8)') 'rx = ', rx
end do
End Program TestRandom1
Context:
$
$ uname -s -m -r
Linux 5.13.9-100.fc33.x86_64 x86_64
$
$ gfortran --version
GNU Fortran (GCC) 10.3.1 20210422 (Red Hat 10.3.1-1)
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$
Testing:
$
$ random1.x
size of random seed (in integers): 8
rx = 0.23642105
rx = 0.39820033
rx = 0.62709534
$
$ random1.x
size of random seed (in integers): 8
rx = 0.84118658
rx = 0.45977014
rx = 0.09513164
$
$ random1.x
size of random seed (in integers): 8
rx = 0.33584720
rx = 0.86550051
rx = 0.26546007
$
A seed size of 8*32 = 256 bits looks consistent with the xoshiro256 algorithm mentioned here in the GNU Fortran documentation.
Upvotes: 4