| Hosted by CoCalc | Download
Kernel: Python 3 (Ubuntu Linux)

Calculating π\pi

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

import matplotlib.pyplot as plt import numpy as np
xx, yy = 2 * np.random.rand(2, 10000) -1
inner = xx**2 + yy**2 < 1
4 * inner.sum() / xx.shape[0]
3.1468
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')
Image in a Jupyter notebook

bit more accuracy ...

from numba import jit
@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
approx = [approx_pi() for i in range(1000)] sum(approx) / len(approx)
3.1415741919999958