https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan(1) = pi / 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedia.org/wiki/Leibniz_formu
(limit: int)
| 1 | def calculate_pi(limit: int) -> str: |
| 2 | """ |
| 3 | https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 |
| 4 | Leibniz Formula for Pi |
| 5 | |
| 6 | The Leibniz formula is the special case arctan(1) = pi / 4. |
| 7 | Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. |
| 8 | |
| 9 | Convergence (https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence) |
| 10 | |
| 11 | We cannot try to prove against an interrupted, uncompleted generation. |
| 12 | https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Unusual_behaviour |
| 13 | The errors can in fact be predicted, but those calculations also approach infinity |
| 14 | for accuracy. |
| 15 | |
| 16 | Our output will be a string so that we can definitely store all digits. |
| 17 | |
| 18 | >>> import math |
| 19 | >>> float(calculate_pi(15)) == math.pi |
| 20 | True |
| 21 | |
| 22 | Since we cannot predict errors or interrupt any infinite alternating series |
| 23 | generation since they approach infinity, or interrupt any alternating series, we'll |
| 24 | need math.isclose() |
| 25 | |
| 26 | >>> math.isclose(float(calculate_pi(50)), math.pi) |
| 27 | True |
| 28 | >>> math.isclose(float(calculate_pi(100)), math.pi) |
| 29 | True |
| 30 | |
| 31 | Since math.pi contains only 16 digits, here are some tests with known values: |
| 32 | |
| 33 | >>> calculate_pi(50) |
| 34 | '3.14159265358979323846264338327950288419716939937510' |
| 35 | >>> calculate_pi(80) |
| 36 | '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' |
| 37 | """ |
| 38 | # Variables used for the iteration process |
| 39 | q = 1 |
| 40 | r = 0 |
| 41 | t = 1 |
| 42 | k = 1 |
| 43 | n = 3 |
| 44 | m = 3 |
| 45 | |
| 46 | decimal = limit |
| 47 | counter = 0 |
| 48 | |
| 49 | result = "" |
| 50 | |
| 51 | # We can't compare against anything if we make a generator, |
| 52 | # so we'll stick with plain return logic |
| 53 | while counter != decimal + 1: |
| 54 | if 4 * q + r - t < n * t: |
| 55 | result += str(n) |
| 56 | if counter == 0: |
| 57 | result += "." |
| 58 | |
| 59 | if decimal == counter: |
| 60 | break |