summaryrefslogtreecommitdiff
path: root/Computing Pi.py
blob: 6f6e08cdf7f9905a2ec605a5a5010addd22a9e62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import time
def calculate_next_square_root(number, square_root):
    next_square_root = ((number / square_root) + square_root) / 2
    return next_square_root

def calculate_square_root(number, digits, add):
    square_root = 1 * (10 ** (digits + add))
    next_square_root = calculate_next_square_root(number=number, square_root=square_root)
    while (next_square_root != square_root):
        square_root = next_square_root
        next_square_root = calculate_next_square_root(number=number, square_root=square_root)
    return square_root
def calculate_next_pi(a, b, t, digits, add):
    next_pi = ((10 ** (digits + add)) * ((a + b) ** 2)) / (4 * t)
    return next_pi
digits = int(input('How many digits of pi? '))
add = digits
a = 10 ** (digits + add)
b = calculate_square_root(number=(10 ** ((digits + add) * 2)) / 2, digits=digits, add=add)
t = (10 ** ((digits + add) * 2)) / 4
p = 1
pi = -1
n = 0
next_pi = calculate_next_pi(a=a, b=b, t=t, digits=digits, add=add)
while True:
    try:
        while (next_pi != pi):
            pi = next_pi
            next_a = (a + b) / 2
            next_b = calculate_square_root(number=a * b, digits=digits, add=add)
            next_t = t - (p * ((a - next_a) ** 2))
            next_p = 2 * p
            a = next_a
            b = next_b
            t = next_t
            p = next_p
            next_pi = calculate_next_pi(a=a, b=b, t=t, digits=digits, add=add)
            n += 1
        pi /= (10 ** add)
        pi = [int(i) for i in str(pi)]

        
    except KeyboardInterrupt:
        print ('\n',pi)
        quit()