46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
|
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()
|