Skip to content

Instantly share code, notes, and snippets.

@jasonacox
Created March 12, 2024 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonacox/dfc3f1c1d4e630009c80797352d81c32 to your computer and use it in GitHub Desktop.
Save jasonacox/dfc3f1c1d4e630009c80797352d81c32 to your computer and use it in GitHub Desktop.
Calculate Pi to a defined number of decimal places using Archimedes method.
from decimal import Decimal, getcontext
def pi_archimedes(n):
"""
Calculate Pi using Archimedes method with n iterations to estimate Pi.
This method approximates Pi by calculating the perimeter of a polygon inscribed
within a unit circle.
Polygon edge lengths are computed using the Pythagorean theorem and the geometry of the polygons.
The number of sides of the polygon is also doubled in each iteration, as each side of the
polygon is bisected to form a new polygon with twice as many sides.
The formula is:
sides = 2 * 2^n
length^2 = 2 - 2 * sqrt(1 - length^2 / 4))
After n iterations, the function returns the approximate value of Pi using the formula:
perimeter = sides * sqrt(length^2)
"""
polygon_edge_length_sq = Decimal(2)
polygon_sides = 2
# Start with a line, then a square, then a octagon, etc.
for _ in range(n):
polygon_edge_length_sq = 2 - 2 * (1 - polygon_edge_length_sq / 4).sqrt()
polygon_sides = polygon_sides * 2
return polygon_sides * polygon_edge_length_sq.sqrt()
# Set the number of decimal places to calculate
PLACES = 100
# Calculate Pi with increasing iterations until the result converges at
# the desired number of decimal places
old_result = None
for n in range(10*PLACES):
getcontext().prec = 2 * PLACES # Do calculations with double precision
result = pi_archimedes(n)
getcontext().prec = PLACES # Print the result with single precision
result = +result # Rounding
print("%3d: %s" % (n, result))
if result == old_result: # Did it converge?
break
old_result = result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment