Stupid Pi tricks for Pi Day
π approximation script, from Stephen Chappell.
import sys def pi(): a, b, c, d, e, f = 1, 0, 1, 1, 3, 3 while True: if a * 4 + b - c < c * e: yield e a, b, c, d, e, f = a * 10, (b - c * e) * 10, c, d, ((a * 3 + b) * 10) // c - e * 10, f else: a, b, c, d, e, f = a * d, (a * 2 + b) * f, c * f, d + 1, ((d * 7 + 2) * a + b * f) // (c * f), f + 2 digit = pi() sys.stdout.write("%d.%d" % (digit.next(), digit.next())) if len(sys.argv) < 2: prec = 5 else: prec = int(sys.argv[1]+1) for i in range(prec): sys.stdout.write("%d" % digit.next()) print
To get Pi with a precision of 10 digits:
python pi_approx.py 10
And here is another script using Machin’s formula.
Comments are closed.