Open in CoCalc with one click!

Calculating π\pi

My personal favourite way of caluclating π\pi ... although probably the worst way imaginable.

In [1]:
import matplotlib.pyplot as plt import numpy as np
In [2]:
xx, yy = 2 * np.random.rand(2, 10000) -1
In [3]:
inner = xx**2 + yy**2 < 1
In [4]:
4 * inner.sum() / xx.shape[0]
3.1468
In [5]:
fig, ax = plt.subplots(1, figsize = (10, 10)) ax.scatter(xx, yy, alpha=.25, marker='.', c = ['r' if i else 'b' for i in inner]) ax.add_patch(plt.Circle((0, 0), 1, facecolor='none', edgecolor='r', linewidth=1, alpha=0.75)) ax.set_aspect('equal')

bit more accuracy ...

In [6]:
from numba import jit
In [7]:
@jit def approx_pi(): xx, yy = 2 * np.random.rand(2, 1000000) -1 inner = xx**2 + yy**2 < 1 pi = 4 * inner.sum() / xx.shape[0] return pi
In [9]:
approx = [approx_pi() for i in range(1000)] sum(approx) / len(approx)
3.1415741919999958
In [ ]: