I have implemented a calculation of Pi in Python, just for the lulz. But now I wonder if I could improve this more. Could you help me out? I do not program a lot in Python.
from time import time
from decimal import *
def faculty(m):
k=m
n=1
while(n<m):
k=k*n
n+=1
if(k>0):
return k
else:
return 1
def ramanujan(b, n):
return b+Decimal(faculty(4*n)*(1103+26390*n))/Decimal((faculty(n)**4)*396**(4*n))
def chudnovsky(b, n):
return b+(((-1)**n)*(faculty(6*n))*(13591409+(545140134*n)))/(faculty(Decimal(3)*n)*(faculty(n)**3)*640320**(3*n+(Decimal(3)/Decimal(2))))
def calc(x, a, func):
b=Decimal(0)
n=Decimal(0)
while(n<x):
b = func(b, n)
n=n+1
return ((a*b)**(-1))
def calcrama():
return calc(20, Decimal((2*Decimal(2).sqrt())/9801), ramanujan)
def calcchud():
return calc(20, 12, chudnovsky)
def save(name, func):
fobj = open(name, "w")
t = time()
pi = func()
t = time() - t
fobj.write("Time: "+str(t)+"\nPi: "+str(pi))
fobj.close()
getcontext().prec = 1000
save("rama.txt", calcrama)
save("chud.txt", calcchud)