import numpy as np
def estimate_pi(n_points: int = 1_000_000) -> float:
"""
Estimate the value of pi using Monte Carlo simulation.
Generates random points in a square from (-1, -1) to (1, 1) and counts
the proportion that fall inside the unit circle (x^2 + y^2 <= 1).
The ratio, multiplied by 4, approximates pi.
Args:
n_points (int): Number of random points to simulate.
Returns:
float: Estimated value of pi.
"""
# Generate random points in the square [-1, 1] x [-1, 1]
x = np.random.uniform(-1, 1, n_points)
y = np.random.uniform(-1, 1, n_points)
# Count points inside the unit circle
inside = np.sum(x**2 + y**2 <= 1)
# Estimate pi
pi_estimate = 4 * inside / n_points
return pi_estimate
if __name__ == "__main__":
n = 10_000_000 # Increase for better accuracy (takes ~1-2 seconds)
pi_est = estimate_pi(n)
print(f"Pi estimate using {n:,} points: {pi_est:.10f}")
print(f"Actual pi: {np.pi:.10f}")
print(f"Error: {abs(pi_est - np.pi):.10f}")
This code is efficient (vectorized with NumPy), customizable, and includes error reporting for validation. For even larger n_points, accuracy improves as ~1/sqrt(N).