# Demo of Liu Hui’s Inscribed Polygon π-Approximation
# Description: use 6,12,24... polygons to inscribe circle, for pi caluation
# Author: Daniel ge
# Date: 2025-05-11
import numpy as np
import matplotlib.pyplot as plt
def draw_inscribed(n):
angles = np.linspace(0, 2*np.pi, n+1)
x, y = np.cos(angles), np.sin(angles)
plt.plot(x, y, '-o', ms=3, label=f"{str(int(n))}-gon")
# outline to inscribe circle
theta = np.linspace(0, 2*np.pi, 300)
plt.plot(np.cos(theta), np.sin(theta), color='gray')
plt.figure(figsize=(9,6))
for n in [6, 12, 24, 36, 48]: # 6, 12,24,36,48 side polygons
draw_inscribed(n)
plt.axis('equal'); plt.axis('off')
plt.title("Inscribed Polygons Approaching the Circle")
plt.legend(loc='lower right')
plt.show()
# Approximation accuracy
ns = [6 * 2**k for k in range(7)] # [6,12,24,...,1536]
perimeters = [n * 2 * np.sin(np.pi / n) for n in ns]
approximations = [P/2 for P in perimeters]
plt.plot(ns, approximations, 'o-', label="P_n/2")
plt.axhline(np.pi, color='gray', linestyle='--', label="π")
plt.xscale('log', base=2)
plt.xlabel("Number of sides (n)")
plt.ylabel("Approximation of π")
plt.title("Liu Hui’s Inscribed Polygon π-Approximation")
plt.legend()
plt.grid(True, ls='--', alpha=0.5)
plt.show()