Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created December 11, 2024 15:02
Show Gist options
  • Save adrianosferreira/03c14da6f38c0387a091411ee4a67c9b to your computer and use it in GitHub Desktop.
Save adrianosferreira/03c14da6f38c0387a091411ee4a67c9b to your computer and use it in GitHub Desktop.
Estimating PI using the algorithm from Srinivasa Ramanujan
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())
@adrianosferreira
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment