Here’s a #bash script I saved as “pi” somewhere in $PATH
#!/bin/bash
echo "scale=$1;a(1)*4" | bc -l
I demonstrate it this way:
$ for i in {1..20}; do pi $i; done
2.8 3.12 3.140 3.1412 3.14156 3.141592 3.1415924 3.14159264 3.141592652 3.1415926532 3.14159265356 3.141592653588 3.1415926535896 3.14159265358976 3.141592653589792 3.1415926535897932 3.14159265358979320 3.141592653589793236 3.1415926535897932384 3.14159265358979323844
π 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]}")
