Created
December 11, 2024 15:02
-
-
Save adrianosferreira/03c14da6f38c0387a091411ee4a67c9b to your computer and use it in GitHub Desktop.
Estimating PI using the algorithm from Srinivasa Ramanujan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def factorial(n): | |
if n == 0: | |
return 1 | |
else: | |
result = n * factorial(n-1) | |
return result | |
def estimate_pi(): | |
total = 0 | |
k = 0 | |
factor = 2 * math.sqrt(2) / 9801 | |
while True: | |
num = factorial(4*k) * (1103 + 26390 * k) | |
den = factorial(k) ** 4 * 396 ** (4*k) | |
total += num / den | |
term = factor * num/den | |
if abs(term) < 1e-15: | |
break | |
k += 1 | |
return factor * total | |
print(estimate_pi()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://en.wikipedia.org/wiki/Pi