Preview:
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))
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter