calculate pi using monte carlo in python

To calculate an estimate of pi using the Monte Carlo method in Python, we need to do the following steps:

  1. Generate random points in the square from (0,0) to (1,1)
  2. Determine how many of these points are inside a quarter circle within that square whose radius is 1 (i.e., points such that x^2 + y^2 <= 1)
  3. Multiply the ratio of points inside the quarter circle to the total number of generated points by 4 to obtain an estimate of pi.

Here's the code to implement the above method in Python:

main.py
import random

def estimate_pi(n):
    """Estimate pi using Monte Carlo simulation with n points."""
    num_points_inside = 0
    for i in range(n):
        x = random.random()  # generate a random x-coordinate
        y = random.random()  # generate a random y-coordinate
        if x*x + y*y <= 1:   # if the point is inside the circle
            num_points_inside += 1
    pi_estimate = 4 * num_points_inside / n
    return pi_estimate
441 chars
13 lines

In the above code, estimate_pi(n) takes as input the number n of points to generate and returns an estimate of pi using the Monte Carlo method. The function generates n random points in the square from (0,0) to (1,1) and checks whether each point is inside the quarter circle within that square whose radius is 1. The variable num_points_inside keeps track of the number of generated points that are inside the quarter circle. Finally, the ratio of num_points_inside to n is multiplied by 4 to obtain the final estimate of pi.

Example usage:

main.py
print(estimate_pi(10000))
26 chars
2 lines

This will generate 10,000 random points and return an estimate of pi using the Monte Carlo method based on those points. The estimate will be accurate to within a few decimal places.

related categories

gistlibby LogSnag