!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!  Program file name: monte.f90                                           !
!                                                                         !
!  © Tao Pang 2006                                                        !
!                                                                         !
!  Last modified: November 13, 2009                                       !
!                                                                         !
!  (1) This F90 program is created for the book, "An Introduction to      !
!      Computational Physics, 2nd Edition," written by Tao Pang and       !
!      published by Cambridge University Press on January 19, 2006.       !
!                                                                         !
!  (2) No warranties, express or implied, are made for this program.      !
!                                                                         !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
MODULE CSEED
  INTEGER :: SEED
END MODULE CSEED
!
PROGRAM MONTE 
!
! An example of integration with direct Monte Carlo scheme
! with integrand f(x) = x*x.
!
  USE CSEED
  IMPLICIT NONE
  INTEGER, PARAMETER :: N = 1000000
  INTEGER :: I
  INTEGER, DIMENSION (8) :: T
  REAL :: X, F, S0, DS, FX, RANF
!
! Initiate the seed from the current date and time
!
  CALL DATE_AND_TIME(VALUES = T)
  SEED = T(1)+70*(T(2)+12*(T(3)+31*(T(5)+23*(T(6)+59*T(7)))))
  IF (MOD(SEED,2).EQ.0) SEED = SEED-1
!
  S0 = 0.0
  DS = 0.0
  DO I = 1, N
    X = RANF()
    F = FX(X)
    S0 = S0 + F
    DS = DS + F*F
  END DO
  S0 = S0/N
  DS = DS/N
  DS = SQRT(ABS(DS-S0*S0)/N)
  WRITE(6, *) "S =", S0, "+-", DS
END PROGRAM MONTE
!
FUNCTION FX(X) RESULT (F)
  IMPLICIT NONE
  REAL :: X, F
!
  F = X*X
END FUNCTION FX
!
FUNCTION RANF() RESULT (CR)
!
! Function to generate a uniform random number in [0,1]
! following x(i+1)=a*x(i) mod c with a=7** 5 and
! c=2**31-1.  Here the seed is a global variable.
!
  USE CSEED
  IMPLICIT NONE
  INTEGER :: H, L, T, A, C, Q, R
  DATA A/16807/, C/2147483647/, Q/127773/, R/2836/
  REAL :: CR
!
  H = SEED/Q
  L = MOD(SEED, Q)
  T = A*L - R*H
  IF (T .GT. 0) THEN
    SEED = T
  ELSE
    SEED = C + T
  END IF
  CR = SEED/FLOAT(C)
END FUNCTION RANF
