# Author: Muhammad Ahmad Tirmazi
# Date: January 4, 2014
from decimal import *
import math
class PiCalculator(): #Calculates Pi
def __init__(self, prec):
getcontext().prec = prec # the precision
return
def nilakantha(self, end): # Nilakantha's series
op = '+'
x = Decimal(3)
for n in range(2, end, 2):
if (op == '-'):
x -= ( Decimal(4) / Decimal((n * (n+1) * (n+2))) )
op = '+'
else:
x += ( Decimal(4) / Decimal((n * (n+1) * (n+2))) )
op = '-'
return x
def gregory_leibniz(self, end): # Gregory-Leibniz's series
op = '+'
x = Decimal(0)
for n in range(1, end):
if (op == '-'):
x -= ( Decimal(4) / Decimal(2*n - 1) )
op = '+'
else:
x += ( Decimal(4) / Decimal(2*n - 1) )
op = '-'
return x
def ramanujan(self, end): # Ramanujan's series
y = Decimal(0)
for n in range(0, end):
y += ( Decimal(math.factorial(4*n)) * Decimal((1103 + 26390*n)) )\
/ (Decimal(math.pow( Decimal(math.factorial(n)), 4)) \
* Decimal(math.pow(396, 4*n)) )
y *= ( Decimal(2) * Decimal(math.sqrt(2)) ) / Decimal(9801)
y = Decimal(1/y)
return y
def chudnovsky(self, end):
y = Decimal(0)
for n in range(0, end):
y += ( Decimal(math.factorial(6*n)) * \
Decimal((13591409 + 545140134*n)) )\
/ ( Decimal(math.pow( \
Decimal(math.factorial(3*n)) * Decimal(math.factorial(n)), 3)) \
* Decimal(math.pow(-640320, 3*n)) )
y *= ( Decimal(12) / Decimal(math.pow(640320, 1.5)) )
y = Decimal(1/y)
return y
def in_built(self): # Stored Value by Python implementation
return Decimal(math.pi)