algorithms for calculating pi in python

Solutions on MaxInterview for algorithms for calculating pi in python by the best coders in the world

showing results for - "algorithms for calculating pi in python"
Maya
07 May 2019
1from decimal import *
2
3#Sets decimal to 25 digits of precision
4getcontext().prec = 25
5
6def factorial(n):
7    if n<1:
8        return 1
9    else:
10        return n * factorial(n-1)
11
12def plouffBig(n): #http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
13    pi = Decimal(0)
14    k = 0
15    while k < n:
16        pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6)))
17        k += 1
18    return pi
19
20def bellardBig(n): #http://en.wikipedia.org/wiki/Bellard%27s_formula
21    pi = Decimal(0)
22    k = 0
23    while k < n:
24        pi += (Decimal(-1)**k/(1024**k))*( Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) -Decimal(1)/(4*k+3))
25        k += 1
26    pi = pi * 1/(2**6)
27    return pi
28
29def chudnovskyBig(n): #http://en.wikipedia.org/wiki/Chudnovsky_algorithm
30    pi = Decimal(0)
31    k = 0
32    while k < n:
33        pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
34        k += 1
35    pi = pi * Decimal(10005).sqrt()/4270934400
36    pi = pi**(-1)
37    return pi
38print "\t\t\t Plouff \t\t Bellard \t\t\t Chudnovsky"
39for i in xrange(1,20):
40    print "Iteration number ",i, " ", plouffBig(i), " " , bellardBig(i)," ", chudnovskyBig(i)
41
42
43