Last active
March 29, 2024 00:05
-
-
Save hdf/8d860c044171543919bcae8c2e22deb1 to your computer and use it in GitHub Desktop.
Bellard's formula for calculating PI in Python
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 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)) |
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
You use
k
inbellard(n)
, rather thann
. This causes errors if the function is called in any other context than withk
and insidebellard.py