2025年7月16日水曜日

Please post the Python code to probabilistically calculate Pi using the Monte Carlo method.

 Python

import random

def estimate_pi_monte_carlo(num_points):
    """
    Probabilistically estimates Pi using the Monte Carlo method.

    This method simulates randomly "throwing darts" at a square board.
    A quarter circle is inscribed within the square. The ratio of darts
    landing inside the quarter circle to the total number of darts
    approximates the ratio of the quarter circle's area to the square's area (Pi/4).

    Args:
        num_points (int): The total number of random points (darts) to generate.

    Returns:
        float: The estimated value of Pi.
    """
    inside_circle_count = 0

    for _ in range(num_points):
        # Generate random x and y coordinates between 0 and 1
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)

        # Calculate the squared distance from the origin (0,0)
        # We use squared distance to avoid a computationally expensive square root
        distance_squared = x**2 + y**2

        # Check if the point falls within the quarter circle (radius 1)
        if distance_squared <= 1:
            inside_circle_count += 1

    # The ratio (inside_circle_count / num_points) approximates Pi/4.
    # Therefore, Pi is approximately 4 * (inside_circle_count / num_points).
    pi_estimate = 4 * (inside_circle_count / num_points)
    return pi_estimate

if __name__ == "__main__":
    print("--- Monte Carlo Pi Estimation ---")

    # Experiment with different numbers of points
    points_1 = 1000
    pi_result_1 = estimate_pi_monte_carlo(points_1)
    print(f"Estimated Pi with {points_1} points: {pi_result_1:.6f}")

    points_2 = 100000
    pi_result_2 = estimate_pi_monte_carlo(points_2)
    print(f"Estimated Pi with {points_2} points: {pi_result_2:.6f}")

    points_3 = 1000000
    pi_result_3 = estimate_pi_monte_carlo(points_3)
    print(f"Estimated Pi with {points_3} points: {pi_result_3:.6f}")

    points_4 = 10000000
    pi_result_4 = estimate_pi_monte_carlo(points_4)
    print(f"Estimated Pi with {points_4} points: {pi_result_4:.6f}")

    # Compare with Python's built-in Pi value
    import math
    print(f"\nActual Pi (math.pi): {math.pi:.6f}")

Code Explanation

This Python code uses the Monte Carlo method to approximate the value of Pi. Here's how it works:

  • import random: This line imports the random module, which is essential for generating random numbers.

  • estimate_pi_monte_carlo(num_points) function:

    • num_points: This argument specifies the total number of random "darts" or points to generate within the simulation. A higher number of points generally leads to a more accurate approximation of Pi.

    • inside_circle_count = 0: This variable keeps track of how many of the generated points fall within the inscribed quarter circle.

    • for _ in range(num_points):: This loop iterates num_points times, with each iteration simulating one "dart throw."

    • x = random.uniform(0, 1) and y = random.uniform(0, 1): These lines generate random floating-point numbers for the x and y coordinates. Both x and y will be between 0 (inclusive) and 1 (inclusive), effectively placing the "dart" randomly within a 1x1 square.

    • distance_squared = x**2 + y**2: This calculates the square of the distance from the origin (0,0) to the randomly generated point (x,y). We use the squared distance to avoid computing the square root (math.sqrt), which is computationally more expensive and unnecessary for comparison against a squared radius of 1.

    • if distance_squared <= 1:: This condition checks if the generated point falls within the quarter circle. Since the quarter circle has a radius of 1, any point whose distance from the origin is 1 or less is inside or on the boundary of the quarter circle.

    • inside_circle_count += 1: If the point is inside the quarter circle, this counter is incremented.

    • pi_estimate = 4 * (inside_circle_count / num_points): Finally, the estimated value of Pi is calculated. The ratio of points inside the quarter circle (inside_circle_count / num_points) approximates the ratio of the quarter circle's area (pi/4) to the square's area (1). Therefore, multiplying this ratio by 4 gives an approximation of Pi.

  • if __name__ == "__main__": block:

    • This standard Python construct ensures the code inside this block only runs when the script is executed directly (not when imported as a module).

    • It demonstrates the estimate_pi_monte_carlo function with various num_points values, showing how the accuracy generally improves with more points.

    • import math: This imports the math module, allowing access to math.pi, Python's built-in, highly precise value of Pi for comparison.

This Monte Carlo simulation provides an intuitive way to understand how randomness can be used to solve mathematical problems. While it's generally less efficient for calculating Pi to a very high precision compared to deterministic algorithms, its simplicity and applicability to various problems make it a powerful concept.

0 件のコメント:

コメントを投稿