Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute Pi with Klingenstierna's formula.
#! /usr/local/bin/python3.6
"""
Computation of Pi with Klingenstierna's formula
"""
import sys
import time
import traceback
class CalcPiKlingenstierna:
L = 10000 # Digits of computation
FNAME = "pi_klingenstierna.txt"
def __init__(self):
self.l1 = int(self.L / 8) + 1
self.n = int((self.L + 1) / 2) + 1
def compute(self):
""" Computation of Pi """
try:
t0 = time.time()
s = [0 for _ in range(self.l1 + 2)]
a = [0 for _ in range(self.l1 + 2)]
b = [0 for _ in range(self.l1 + 2)]
c = [0 for _ in range(self.l1 + 2)]
q = [0 for _ in range(self.l1 + 2)]
a[0] = 32 * 10
b[0] = 4 * 239
c[0] = 16 * 515
for k in range(1, self.n + 1):
a = self.__long_div(a, 10 * 10)
b = self.__long_div(b, 239 * 239)
c = self.__long_div(c, 515 * 515)
q = self.__long_sub(a, b)
q = self.__long_sub(q, c)
q = self.__long_div(q, 2 * k - 1)
if k % 2 == 0:
s = self.__long_sub(s, q)
else:
s = self.__long_add(s, q)
t1 = time.time()
tt = t1 - t0
self.__display(tt, s)
except Exception as e:
raise
def __long_add(self, a, b):
""" Computation of long + long
:param list a
:param list b
:return list z
"""
try:
z = [0 for _ in range(self.n)]
cr = 0
for i in reversed(range(self.l1 + 2)):
z[i] = a[i] + b[i] + cr
if z[i] < 100000000:
cr = 0
else:
z[i] -= 100000000
cr = 1
return z
except Exception as e:
raise
def __long_sub(self, a, b):
""" Computation of long - long
:param list a
:param list b
:return list z
"""
try:
z = [0 for _ in range(self.n)]
br = 0
for i in reversed(range(self.l1 + 2)):
z[i] = a[i] - b[i] - br
if z[i] >= 0:
br = 0
else:
z[i] += 100000000
br = 1
return z
except Exception as e:
raise
def __long_div(self, a, b):
""" Computation of long / short
:param list a
:param list b
:return list z
"""
try:
z = [0 for _ in range(self.n)]
r = 0
for i in range(self.l1 + 2):
w = a[i]
z[i] = int((w + r) / b)
r = ((w + r) % b) * 100000000
return z
except Exception as e:
raise
def __display(self, tt, s):
""" Display
:param float tt
:param list s
"""
try:
print("** Pi Computation with the Klingenstierna formula method **")
print(" Digits = {:d}.".format(self.L))
print(" Time = {:f} seconds".format(tt))
out_file = open(self.FNAME, "w")
out_file.write("** Pi Computation with the Klingenstierna formula method **\n")
out_file.write(" Digits = {:d}.\n".format(self.L))
out_file.write(" Time = {:f} seconds.\n\n".format(tt))
out_file.write(" {:d}.\n".format(s[0]))
for i in range(1, self.l1):
if i % 10 == 1:
out_file.write("{:08d}:".format((i - 1) * 8 + 1))
out_file.write(" {:08d}".format(s[i]))
if i % 10 == 0:
out_file.write("\n")
out_file.close
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = CalcPiKlingenstierna()
obj.compute()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.