|
| 1 | +""" |
| 2 | +Name: pi.py |
| 3 | +Purpose: Get the value of Pi to n number of decimal places |
| 4 | +Author: Pradipta (geekpradd) |
| 5 | +Algorithm: Chudnovsky Algorithm |
| 6 | +License: MIT |
| 7 | +
|
| 8 | +Module Dependencies: |
| 9 | +
|
| 10 | +Math provides fast square rooting |
| 11 | +Decimal gives the Decimal data type which is much better than Float |
| 12 | +sys is needed to set the depth for recursion. |
| 13 | +""" |
| 14 | +import math, sys |
| 15 | +from decimal import * |
| 16 | +getcontext().rounding = ROUND_FLOOR |
| 17 | +sys.setrecursionlimit(100000) |
| 18 | +if sys.version_info[0] == 2: |
| 19 | + input = raw_input |
| 20 | + |
| 21 | +def factorial(n): |
| 22 | + """ |
| 23 | + Return the Factorial of a number using recursion |
| 24 | +
|
| 25 | + Parameters: |
| 26 | + n -- Number to get factorial of |
| 27 | + """ |
| 28 | + if not n: |
| 29 | + return 1 |
| 30 | + return n*factorial(n-1) |
| 31 | + |
| 32 | + |
| 33 | +def getIteratedValue(k): |
| 34 | + """ |
| 35 | + Return the Iterations as given in the Chudnovsky Algorithm. |
| 36 | + k iterations gives k-1 decimal places.. Since we need k decimal places |
| 37 | + make iterations equal to k+1 |
| 38 | + |
| 39 | + Parameters: |
| 40 | + k -- Number of Decimal Digits to get |
| 41 | + """ |
| 42 | + k = k+1 |
| 43 | + getcontext().prec = k |
| 44 | + sum=0 |
| 45 | + for k in range(k): |
| 46 | + first = factorial(6*k)*(13591409+545140134*k) |
| 47 | + down = factorial(3*k)*(factorial(k))**3*(640320**(3*k)) |
| 48 | + sum += first/down |
| 49 | + return Decimal(sum) |
| 50 | + |
| 51 | +def getValueOfPi(k): |
| 52 | + """ |
| 53 | + Returns the calculated value of Pi using the iterated value of the loop |
| 54 | + and some division as given in the Chudnovsky Algorithm |
| 55 | +
|
| 56 | + Parameters: |
| 57 | + k -- Number of Decimal Digits upto which the value of Pi should be calculated |
| 58 | + """ |
| 59 | + iter = getIteratedValue(k) |
| 60 | + up = 426880*math.sqrt(10005) |
| 61 | + pi = Decimal(up)/iter |
| 62 | + |
| 63 | + return pi |
| 64 | + |
| 65 | +def shell(): |
| 66 | + """ |
| 67 | + Console Function to create the interactive Shell. |
| 68 | + Runs only when __name__ == __main__ that is when the script is being called directly |
| 69 | +
|
| 70 | + No return value and Parameters |
| 71 | + """ |
| 72 | + 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") |
| 73 | + |
| 74 | + while True: |
| 75 | + print (">>> ", end='') |
| 76 | + entry = input() |
| 77 | + if entry == "quit": |
| 78 | + break |
| 79 | + if not entry.isdigit(): |
| 80 | + print ("You did not enter a number. Try again") |
| 81 | + else: |
| 82 | + print (getValueOfPi(int(entry))) |
| 83 | + |
| 84 | +if __name__=='__main__': |
| 85 | + shell() |
0 commit comments