Skip to content

Instantly share code, notes, and snippets.

@hdf
Last active March 29, 2024 00:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hdf/8d860c044171543919bcae8c2e22deb1 to your computer and use it in GitHub Desktop.
Save hdf/8d860c044171543919bcae8c2e22deb1 to your computer and use it in GitHub Desktop.
Bellard's formula for calculating PI in Python
import sys
from decimal import Decimal, getcontext
k = int(sys.argv[1]) if len(sys.argv) > 1 else 70
def bellard(n):
getcontext().prec = n + 1
return Decimal(1.0/(2**6)) * sum([Decimal(-1)**k/(1024**k) * (Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) - Decimal(1)/(4*k+3)) for k in range(n)])
print(bellard(k))
@UmbralReaper
Copy link

You use k in bellard(n), rather than n. This causes errors if the function is called in any other context than with k and inside bellard.py

@UmbralReaper
Copy link

Actually, I was wrong. I missed that you used k as in for k in range(n).

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