How to calculate the value of pi using Python?

In Python, you can use the Monte Carlo method to estimate the value of pi. Here are the specific steps:

  1. Generate a large number of points randomly within a unit square.
  2. Count the number of points falling within the unit circle.
  3. By comparing the area of the unit circle (π/4) and the area of the unit square, we can approximate the value of π.

Here is a simple code example implemented in Python:

import random

def estimate_pi(num_points):
    points_inside_circle = 0
    for _ in range(num_points):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        if x**2 + y**2 <= 1:
            points_inside_circle += 1
    
    pi_estimate = 4 * points_inside_circle / num_points
    return pi_estimate

num_points = 1000000
pi_approx = estimate_pi(num_points)
print("Approximated value of pi:", pi_approx)

In the example above, we generated 1 million points and estimated the value of pi by counting the number of points that fell within the unit circle. You can try adjusting the value of num_points to get a more accurate estimation.

bannerAds