Here's one way to write a Python program that simulates approximating the value of pi using the Monte Carlo method:
code
import random
def monte_carlo_pi(iterations):
inside_circle = 0
for _ in range(iterations):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
distance = (x ** 2 + y ** 2) ** 0.5
if distance <= 1:
inside_circle += 1
return (4 * inside_circle) / iterations
if __name__ == "__main__":
num_iterations = 1000000
estimated_pi = monte_carlo_pi(num_iterations)
print(f"Estimated value of pi after {num_iterations} iterations: {estimated_pi}")
This program generates a large number of random points in a 2x2 square, and then checks if each point is inside a unit circle centered at the origin. It then uses the ratio of the number of points inside the circle to the total number of points to estimate the value of pi. The more iterations you run, the closer the estimate will be to the true value of pi.
You can also use the math library's pi value to check the accuracy of your approximation:
code
import math
import random
def monte_carlo_pi(iterations):
inside_circle = 0
for _ in range(iterations):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
distance = (x ** 2 + y ** 2) ** 0.5
if distance <= 1:
inside_circle += 1
return (4 * inside_circle) / iterations
if __name__ == "__main__":
num_iterations = 1000000
estimated_pi = monte_carlo_pi(num_iterations)
print(f"Estimated value of pi after {num_iterations} iterations: {estimated_pi}")
print(f"Error: {abs(estimated_pi - math.pi)}")
The above code will give you the estimated value of pi and the error value which is the difference between the estimated value and the actual value of pi.
Please note that the monte carlo method is a probabilistic method and it will give you an approximate value of pi. The more iterations you run the more accurate the approximation will be. However, it will never give you the exact value of pi.