! Alexander Sage !Date: 11/9/11 !HW: 5 !Purpose: To use the Monte Carlo method to integrate x**2 program carlos implicit none integer :: i, iseed, a !loup index and seed for subroutine real :: xp, yp !points given by the random number generator real :: fx !point on the curve real :: und !number of points under or the curve real :: value1 real :: func a = 10000000 !any smaller values for a were producing weird results. For the most part the value converged und = 0 ! to the correct answer for the integral write (*,*) ' Enter Seed' !put in a seed to start the random number generator read (*,*) iseed call seed (iseed) Do i = 1, a, 1 call random0 (xp) !get first two random numbers call random0 (yp) fx = func(xp) !find the y value of the funcion at the randomly assigned x value if (fx >= yp) then und = und + 1 !adding up the points under the curve end if end do !closing all the proceedures value1 = real(und) / (1.0*real(a)) !finding the ratio to give the value of the area write (*,*) 'The integral of f(x) = x**2 on 0<=x<=1 is', value1 !giving a value for the integral stop end program Carlos real function func(x) !defining the function to use implicit none real, intent(in) :: x func = x**2 return end function func MODULE ran001 ! ! Purpose: ! To declare data shared between subs random0 and seed. ! ! Record of revisions: ! Date Programmer Description of change ! ==== ========== ===================== ! 11/22/06 S. J. Chapman Original code ! IMPLICIT NONE SAVE INTEGER :: n = 9876 END MODULE ran001 !***************************************************************** !***************************************************************** SUBROUTINE random0 ( ran ) ! ! Purpose: ! Subroutine to generate a pseudorandom number with a uniform ! distribution in the range 0. <= ran < 1.0. ! ! Record of revisions: ! Date Programmer Description of change ! ==== ========== ===================== ! 11/22/06 S. J. Chapman Original code ! USE ran001 ! Shared seed IMPLICIT NONE ! Data dictionary: declare calling parameter types & definitions REAL, INTENT(OUT) :: ran ! Random number ! Calculate next number n = MOD (8121 * n + 28411, 134456 ) ! Generate random value from this number ran = REAL(n) / 134456. END SUBROUTINE random0 !***************************************************************** !***************************************************************** SUBROUTINE seed ( iseed ) ! ! Purpose: ! To set the seed for random number generator random0. ! ! Record of revisions: ! Date Programmer Description of change ! ==== ========== ===================== ! 11/22/06 S. J. Chapman Original code ! USE ran001 ! Shared seed IMPLICIT NONE ! Data dictionary: declare calling parameter types & definitions INTEGER, INTENT(IN) :: iseed ! Value to initialize sequence ! Set seed n = ABS ( iseed ) END SUBROUTINE seed