What's Wrong with My Monte Carlo Calculation of π Using Fortran?

  • Context: Fortran 
  • Thread starter Thread starter Taylor_1989
  • Start date Start date
  • Tags Tags
    Calculation Monte carlo
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
Taylor_1989
Messages
400
Reaction score
14
Hi guys, I am having trouble seeing where I have actually gone wrong with my code. If I run the code I am getting approximation of 12 as my lowest is way to big. But I am really struggling to find where I have gone wrong. Any advice would be appreciated.

Fortran:
PROGRAM assign_10_1

IMPLICIT NONE

INTEGER, DIMENSION (1:12) :: SEED

REAL:: A,X,Y

INTEGER:: I, N, COUNTER_CIRCULE, COUNTER_SQUARE

COUNTER_CIRCULE=0

COUNTER_SQUARE=0

N=100000

WRITE(*,*)'please seclect 12 numbers for your seed'

READ(*,*) SEED

WRITE(*,*) SEED

 CALL RANDOM_SEED(PUT=SEED)

DO I=1,N
   CALL RANDOM_NUMBER(X)
   CALL RANDOM_NUMBER(Y)
   WRITE(*,*) X,Y

   IF (X**2+Y**2 < 1) THEN
   COUNTER_CIRCULE=COUNTER_CIRCULE+1
   ELSE
   COUNTER_SQUARE=COUNTER_SQUARE+1
   END IF

END DO

A=4*(COUNTER_CIRCULE/COUNTER_SQUARE)

WRITE(*,*)'ESTIMATION FOR VALUE OF PI', A
END PROGRAM
 
Physics news on Phys.org
Ok thanks guys. I got it. I just went back of the math with a bit of paper and it clicked in what you are saying. Thanks once again.
 
Baluncore said:
A=4*(COUNTER_CIRCULE / N)
Not mentioned is the fact that if COUNTER_CIRCULE is 1000, then A will be assigned the value 0. In Fortran, C, C++, and many other programming languages, there are two types of division: integer division and floating point division. So for example, 2/5 is 0 while all three of the following expressions evaluate to 0.4 or something close to it.
  • 2.0 / 5.0
  • 2 / 5.0
  • 2.0 / 5
See http://www.oc.nps.edu/~bird/oc3030_online/fortran/basics/basics.html, in Type Conversion and Mixed-Mode Arithmetic.

BTW there is no such word as "circule" in English.
 
  • Like
Likes   Reactions: Taylor_1989 and BvU
Mark44 said:
Not mentioned is the fact that if COUNTER_CIRCULE is 1000, then A will be assigned the value 0. In Fortran, C, C++, and many other programming languages, there are two types of division: integer division and floating point division. So for example, 2/5 is 0 while all three of the following expressions evaluate to 0.4 or something close to it.
  • 2.0 / 5.0
  • 2 / 5.0
  • 2.0 / 5
See http://www.oc.nps.edu/~bird/oc3030_online/fortran/basics/basics.html, in Type Conversion and Mixed-Mode Arithmetic.

BTW there is no such word as "circule" in English.
Thanks for the advice. much appreciated