Calculating Pi using the Monte Carlo method in Python

<<algorithm

pi

import random
random.seed()
n = int(input('n = '))
k = 0
for j in range(n):
    x = random.random()
    y = random.random()
    if x * x + y * y <= 1:
        k += 1
p = 4 * k / n
print("pi =", p)

 

 

Configuration and Input

  • Code: import random and random.seed()
    • Flowchart: Step 1 (START). These lines initiate the program by importing the necessary random module and initializing the random number generator.
  • Code: n = int(input('n = '))
    • Flowchart: Step 2 (Read: n). The program prompts the user to enter an integer value for n (the total number of trials) and stores it.

Initialization and Main Loop

  • Code: k = 0
    • Flowchart: Step 3 (Part 1: k:=0). The variable k (the counter for points that fall inside the circle) is set to zero.
  • Code: for j in range(n):
    • This Python for loop is set up to iterate exactly n times, logically controlling the simulation's repetition:
      • Part of Step 3 (i:=1): The loop begins its first iteration.
      • Step 7 (i:=i+1): The loop automatically advances its hidden counter (j) to the next iteration.
      • Step 8 (Decision: i≤n): The loop implicitly checks if the total number of iterations has been reached. If j<n, it continues; otherwise, it exits.

Simulation (Inside the Loop)

  • Code: x = random.random()
  • Code: y = random.random()
    • Flowchart: Step 4 (x:=random,y:=random). In each iteration, the program generates two random coordinates (x,y) between 0.0 and 1.0, simulating a point within the unit square quadrant.
  • Code: if x * x + y * y <= 1:
    • Flowchart: Step 5 (Decision: x2+y2≤1). This conditional statement checks if the squared distance of the point from the origin (x2+y2) is less than or equal to 1, meaning the point is inside the unit circle.
  • Code: k += 1
    • Flowchart: Step 6 (k:=k+1). This line executes only if the condition in Step 5 is true, incrementing the hit counter k.

Final Calculation and Output

  • Code: p = 4 * k / n
    • Flowchart: Step 9 (p:=4∗k/n). The approximate value of Pi (p) is calculated by taking the ratio of hits (k) to total trials (n) and multiplying it by 4.
  • Code: print("pi =", p)
    • Flowchart: Step 10 (Write: p). The calculated Pi approximation is displayed to the user.
  • End of Script
    • Flowchart: Step 11 (STOP). The program reaches its natural end and terminates.