Monte Carlo for PI, but for an inscribed square into a circle of radius 1!

PHOTO EMBED

Thu Apr 13 2023 21:36:43 GMT+0000 (Coordinated Universal Time)

Saved by @c0d3c4t #monte #carlo #pi

import random
import math
import matplotlib.pyplot as plt

def estimate_pi(n):
    num_points_square = 0
    num_points_total = 0
    x_inside = []
    y_inside = []
    x_outside = []
    y_outside = []
    for _ in range(n):
        x = random.uniform(-1,1)
        y = random.uniform(-1,1)
        distance = math.sqrt(x**2 + y**2)
        if distance <= 1:
            if abs(x) <= 1/math.sqrt(2) and abs(y) <= 1/math.sqrt(2):
                num_points_square += 1
                x_inside.append(x)
                y_inside.append(y)
            else:
                x_outside.append(x)
                y_outside.append(y)
            num_points_total += 1

    pi_estimate = 2/(num_points_square/num_points_total)

    fig, ax = plt.subplots()
    ax.scatter(x_inside, y_inside, color='g', marker='.')
    ax.scatter(x_outside, y_outside, color='r', marker='.')
    ax.set_aspect('equal')
    plt.show()

    return pi_estimate

print(estimate_pi(1000000))
content_copyCOPY

Had to correct the code which was obtained from ChatGPT, but was giving wrong values for Pi. CGPT had problems, because in this case it's the square inscribed in the circle with radius 1, not vice versa.