Skip to content

Instantly share code, notes, and snippets.

@komasaru komasaru/calc_napier.py
Last active Feb 24, 2018

Embed
What would you like to do?
Python script to compute Napier constant.
#! /usr/local/bin/python3.6
"""
Computation of Napier's constant
"""
import sys
import traceback
class CalcNapier:
L = 1000 # Digits of computation
L1 = int(L / 8) + 1 # Length of list
L2 = L1 + 1 # Length of list + 1
N = 451 # Number of items
def compute(self):
""" Computation of Napier's constant """
try:
s = [0 for _ in range(self.L2 + 1)]
a = [0 for _ in range(self.L2 + 1)]
s[0], a[0] = 1, 1
for k in range(1, self.N + 1):
a = self.__long_div(a, k)
s = self.__long_add(s, a)
self.__display(s)
except Exception as e:
raise
def __long_add(self, a, b):
""" Computation of long + long
:param list a: integral values
:param list b: integral values
:return list z: integral values
"""
try:
z = [0 for _ in range(self.N)]
carry = 0
for i in reversed(range(self.L2 + 1)):
z[i] = a[i] + b[i] + carry
if z[i] < 100000000:
carry = 0
else:
z[i] -= 100000000
carry = 1
return z
except Exception as e:
raise
def __long_div(self, a, b):
""" Computation of long / short
:param list a: integral values
:param list b: integral values
:return list z: integral values
"""
try:
z = [0 for _ in range(self.N)]
r = 0
for i in range(self.L2 + 1):
w = a[i]
z[i] = int(int(w + r) / b)
r = ((w + r) % b) * 100000000
return z
except Exception as e:
raise
def __display(self, s):
""" Display
:param list s: integral values
"""
try:
print("{:7d}. ".format(s[0]), end="")
for i in range(1, self.L1):
print("{:08d} ".format(s[i]), end="")
print()
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = CalcNapier()
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.