Home > other >  FORTRAN beginners random number problems
FORTRAN beginners random number problems

Time:11-16

Just started to learn FORTRAN, by generating algorithm subroutine and the function of the random number, found the three sections of the program runs after the results are different, for advice, what is wrong?
1
The program random
Implicit none
Real: : x
Call random_seed ()! System according to the date and time at random seeds
Call random_number (x)! Every random number is not the same
Write (*, *) x! Output a random number between 0-1
Stop
End the program of the random

After the operation can be normal to generate a random number from 0 to 1

2.
The PROGRAM random2
IMPLICIT NONE

! Real: : A=1
Real: : x
Call the random ()
WRITE (*, *) "random number is" x
STOP
END


SUBROUTINE random ()
IMPLICIT NONE
Real: : x
Call random_seed ()! System according to the date and time at random seeds
Call random_number (x)! Every random number is not the same
The RETURN! Output a random number between 0-1
END SUBROUTINE

This period of running the generated a plus or minus an infinite range of random number

3.
The PROGRAM random3
IMPLICIT NONE
REAL, EXTERNAL: : random
! Real: : A=1
Real: : y
Y=the random ()
WRITE (*, *) "random number is", y
STOP
END


The REAL FUNCTION of random ()
Real: : x
Call random_seed ()! System according to the date and time at random seeds
Call random_number (x)! Every random number is not the same
The RETURN! Output a random number between 0-1
END the FUNCTION

After this period of running result is 0

If there are bosses, glad to be appreciated

CodePudding user response:

Don't look at message when Build? The second warning said, don't give x assignment is to use it; The third said the correspondence didn't return value,
Second, with process is not appropriate, don't know if FORTRAN have pointer, don't know how to change,
Third, have replaced the RETURN with the random try=x,

Now look FORTRAN do man

CodePudding user response:

Fortran, the function parameters of the default always preach reference, if you want to transfer value, to add value: : modified:
SUBROUTINE func (x)
Real value: : x
! .
But this usage if only in Fortran 2003 + standard support, earlier standard don't support, but there are some compiler non-standard extension support by value)
  • Related