Calculating Pi using the Monte Carlo method

 

Pi

 

Po = πr2

P = a2 = (2r)2 = 4r2

 Po      πr2
—— = ——
 P      4r2

 Po      π
—— = —
 P      4

 Po      k
—— ≈ —
 P      n

 π     k
— ≈ —
 4     n

         4k
π 
≈ ——
        n

 

 

Monte Carlo methodImplementation of the algorithm in language: Pascal, C++, Java, Python, JavaScript

 

  1. START - The beginning of the algorithm.
  2. We read the number of points to be generated (sampled).
  3. We reset k - the counter for points contained within the circle of radius 1 (set k=0). We assign the initial value of 1 to the variable i, which counts the number of points sampled (set i=1).
  4. We generate two random numbers in the range from 0 to 1 - the x and y coordinates of the point.
  5. We check if the sampled point with coordinates x,y lies within the circle of radius 1. (Is x2+y2≤1?)
  6. If the condition from point 4 is satisfied, we increase the value of the variable k (the counter for points contained in the circle of radius 1) by 1. If the condition is not met, we skip this step.
  7. We increase the sampled point counter i by 1.
  8. We check whether more points should be sampled (Is i≤number of points?). If yes, we return to step 3 of the algorithm.
  9. We calculate and store the approximate value of π in the variable p (using the formula p=4⋅k/ik​).
  10. We display the result.
  11. STOP - The end of the algorithm.