Finding Pi with a Monte Carlo Simulation & Image Processing (Innovative Approach)
This method combines a Monte Carlo simulation with a bit of image processing to visually and statistically estimate Pi. It's more visually engaging than traditional methods and demonstrates the power of computational statistics.
The Core Idea:
- Generate Random Points: We'll create a large number of random points within a square.
- Inscribe a Circle: Imagine a circle perfectly inscribed within that square (diameter = side of the square).
- Ratio of Areas: The ratio of the circle's area to the square's area is π/4.
- Monte Carlo Estimation: By counting how many random points fall inside the circle versus the total number of points, we can estimate this ratio and, therefore, Pi.
- Image Processing Visualization: We'll represent the points as pixels in an image. Points inside the circle will be one color, points outside another. This creates a visual representation of the estimation process.
Python Implementation:
import random
import math
from PIL import Image
def estimate_pi(num_points, image_size):
"""
Estimates Pi using a Monte Carlo simulation and visualizes it with an image.
Args:
num_points: The number of random points to generate. Higher = more accurate.
image_size: The size of the square image (width and height).
Returns:
An estimate of Pi. Also saves an image showing the points.
"""
# Create a new image
img = Image.new("RGB", (image_size, image_size), "white")
pixels = img.load()
inside_circle = 0
radius = image_size / 2
for _ in range(num_points):
x = random.uniform(0, image_size)
y = random.uniform(0, image_size)
# Calculate distance from the center
distance = math.sqrt((x - radius)**2 + (y - radius)**2)
# Check if the point is inside the circle
if distance <= radius:
inside_circle += 1
pixels[int(x), int(y)] = (0, 0, 255) # Blue for inside
else:
pixels[int(x), int(y)] = (255, 0, 0) # Red for outside
# Estimate Pi
pi_estimate = 4 * (inside_circle / num_points)
# Save the image
img.save("pi_estimation.png")
return pi_estimate
# Example Usage:
num_points = 100000 # Increase for better accuracy
image_size = 500
pi_approx = estimate_pi(num_points, image_size)
print(f"Estimated value of Pi: {pi_approx}")
print(f"Actual value of Pi: {math.pi}")
print("Image saved as pi_estimation.png")
Explanation:
- Import Libraries:
random for generating random numbers, math for square root, and PIL (Pillow) for image manipulation.
estimate_pi Function:
- Takes
num_points and image_size as input.
- Creates a white image using
Image.new().
- Initializes
inside_circle to 0.
- Calculates the radius of the circle.
- Loop: Iterates
num_points times:
- Generates random
x and y coordinates within the square.
- Calculates the distance from the center of the circle (radius, radius).
- If the distance is less than or equal to the radius, the point is inside the circle:
- Increment
inside_circle.
- Set the pixel at (x, y) to blue.
- Otherwise, the point is outside the circle:
- Set the pixel at (x, y) to red.
- Pi Estimation: Calculates Pi using the formula:
4 * (inside_circle / num_points).
- Save Image: Saves the image as "pi_estimation.png".
- Returns the estimated value of Pi.
- Example Usage:
- Sets
num_points and image_size.
- Calls
estimate_pi to get the approximation.
- Prints the estimated and actual values of Pi.
Why this is innovative:
- Visual Representation: The image provides a clear visual understanding of the Monte Carlo method. You can see how the ratio of points inside the circle converges towards the correct value.
- Combines Disciplines: It blends probability/statistics (Monte Carlo) with image processing.
- Engaging: The visual aspect makes it more engaging than purely mathematical approaches.
- Scalability: Increasing
num_points improves accuracy, demonstrating the power of computational methods.
To run this code:
- Install Pillow:
pip install Pillow
- Save: Save the code as a
.py file (e.g., pi_monte_carlo.py).
- Run: Execute the file from your terminal:
python pi_monte_carlo.py
This will generate an image named pi_estimation.png and print the estimated value of Pi to the console. Experiment with different values of num_points to see how the accuracy changes. You'll notice that as you increase the number of points, the image becomes more densely filled with blue, and the estimated value of Pi gets closer to the actual value.