|
| 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