Skip to content

Commit af9103c

Browse files
Merge pull request #285 from Prisha-Mordia/main
Monte Carlo Pi Approximation Code
2 parents 86e3394 + 78ad78a commit af9103c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Math/monte_carlo_pi.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import random
2+
import matplotlib.pyplot as plt
3+
4+
5+
def monte_carlo_pi(num_points):
6+
inside_circle = 0
7+
for _ in range(num_points):
8+
x, y = random.uniform(-1, 1), random.uniform(-1, 1)
9+
if x**2 + y**2 <= 1:
10+
inside_circle += 1
11+
return 4 * inside_circle / num_points
12+
13+
14+
def visualize_monte_carlo(num_points):
15+
inside_x, inside_y = [], []
16+
outside_x, outside_y = [], []
17+
for _ in range(num_points):
18+
x, y = random.uniform(-1, 1), random.uniform(-1, 1)
19+
if x**2 + y**2 <= 1:
20+
inside_x.append(x)
21+
inside_y.append(y)
22+
else:
23+
outside_x.append(x)
24+
outside_y.append(y)
25+
plt.figure(figsize=(6, 6))
26+
plt.scatter(inside_x, inside_y, color="blue", s=1, label="Inside Circle")
27+
plt.scatter(outside_x, outside_y, color="red", s=1, label="Outside Circle")
28+
plt.xlabel("X")
29+
plt.ylabel("Y")
30+
plt.legend(loc="upper right")
31+
plt.title(f"Monte Carlo Pi Approximation with {num_points} Points")
32+
plt.show()
33+
34+
35+
num_points = int(input("Enter the number of points to use for the approximation: "))
36+
pi_estimate = monte_carlo_pi(num_points)
37+
print(f"Approximation of Pi with {num_points} points: {pi_estimate}")
38+
# Uncomment below to visualize
39+
# visualize_monte_carlo(num_points)

0 commit comments

Comments
 (0)