π calculation using a Machin-like arctangent formula
#!/usr/bin/python3
from decimal import Decimal, getcontext
import sys
digits = int(sys.argv[1]) if len(sys.argv) > 1 else 50
getcontext().prec = digits + 5 # a few extra digits to avoid rounding errors
def arctan(x):
"""Compute arctan(1/x) using the Taylor series."""
x = Decimal(x)
x2 = x * x
term = Decimal(1) / x
total = term
n = 1
sign = -1
while True:
term = term / x2
delta = term / (2 * n + 1)
if delta == 0:
break
total += sign * delta
sign *= -1
n += 1
return total
pi = 16 * arctan(5) - 4 * arctan(239)
pi = +pi # unary plus applies current context precision
print(f"Pi to {digits} digits:\n{str(pi)[:digits+2]}")
