- Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathPythonPi.py
More file actions
Latest commit
88 lines (73 loc) · 2.06 KB
/
Copy pathPythonPi.py
File metadata and controls
88 lines (73 loc) · 2.06 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Name: pi.py
Purpose: Get the value of Pi to n number of decimal places
Author: Pradipta (geekpradd)
Algorithm: Chudnovsky Algorithm
License: MIT
Module Dependencies:
Math provides fast square rooting
Decimal gives the Decimal data type which is much better than Float
sys is needed to set the depth for recursion.
"""
from __future__ importprint_function
importmath, sys
fromdecimalimport*
getcontext().rounding=ROUND_FLOOR
sys.setrecursionlimit(100000)
python2=sys.version_info[0] ==2
ifpython2:
input=raw_input
deffactorial(n):
"""
Return the Factorial of a number using recursion
Parameters:
n -- Number to get factorial of
"""
ifnotn:
return1
returnn*factorial(n-1)
defgetIteratedValue(k):
"""
Return the Iterations as given in the Chudnovsky Algorithm.
k iterations gives k-1 decimal places.. Since we need k decimal places
make iterations equal to k+1
Parameters:
k -- Number of Decimal Digits to get
"""
k=k+1
getcontext().prec=k
sum=0
forkinrange(k):
first=factorial(6*k)*(13591409+545140134*k)
down=factorial(3*k)*(factorial(k))**3*(640320**(3*k))
sum+=first/down
returnDecimal(sum)
defgetValueOfPi(k):
"""
Returns the calculated value of Pi using the iterated value of the loop
and some division as given in the Chudnovsky Algorithm
Parameters:
k -- Number of Decimal Digits upto which the value of Pi should be calculated
"""
iter=getIteratedValue(k)
up=426880*math.sqrt(10005)
pi=Decimal(up)/iter
returnpi
defshell():
"""
Console Function to create the interactive Shell.
Runs only when __name__ == __main__ that is when the script is being called directly
No return value and Parameters
"""
print ("Welcome to Pi Calculator. In the shell below Enter the number of digits upto which the value of Pi should be calculated or enter quit to exit")
whileTrue:
print (">>> ", end='')
entry=input()
ifentry=="quit":
break
ifnotentry.isdigit():
print ("You did not enter a number. Try again")
else:
print (getValueOfPi(int(entry)))
if__name__=='__main__':
shell()