4 ms·
Chatgpt, please write a function in python for the nth digit of pi. Sure, here is a function in Python that calculates the nth digit of Pi using the Chudno
by childintime 4y ago
Chatgpt, please write a function in python for the nth digit of pi.
Sure, here is a function in Python that calculates the nth digit of Pi using the Chudnovsky algorithm:
from decimal import *
def nth_digit_of_pi(n):
getcontext().prec = n + 1
C = 426880 * math.sqrt(10005)
M = 1
L = 13591409
X = 1
K = 6
S = L
for i in range(1, n):
M = (K ** 3 - 16 * K) * M // i ** 3
L += 545140134
X *= -262537412640768000
S += Decimal(M * L) / X
K += 12
return +str(S / C)[n]
Seems off, but I learned something: https://www.wikiwand.com/en/Chudnovsky_algorithm https://www.wikiwand.com/en/Chudnovsky_algorithm
- leoff 4y agosince this is Python, `nth_digit_of_pi(-1)` should give us the last number of Pi.
- manojlds 4y agoBut it's not a list
- 4gotunameagain 4y agoTraceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'manojlds' object has no attribute 'humour'. Did you mean: 'joke'?
- manojlds 4y ago[flagged]
- deleted 4y ago[deleted]
- mjd 4y agoGenius.
- _visgean 4y agoHere is an article with an actual implementation https://www.craig-wood.com/nick/articles/pi-chudnovsky/ https://www.craig-wood.com/nick/articles/pi-chudnovsky/
- robinhouston 4y agoInteresting! If you correct the obvious errors, then it appears to calculate 1/pi: >>> from decimal import Decimal >>> import math >>> >>> def nth_digit_of_pi(n): ... getcontext().prec = n + 1 ... C = Decimal(426880 * math.sqrt(10005)) ... M = 1 ... L = 13591409 ... X = 1 ... K = 6 ... S = L ... for i in range(1, n): ... M = (K ** 3 - 16 * K) * M // i ** 3 ... L += 545140134 ... X *= -262537412640768000 ... S += Decimal(M * L) / X ... K += 12 ... return str(S / C)[n] ... >>> "".join([ nth_digit_of_pi(i) for i in range(50) ]) '0.318309886183790698041462054251035408427213165074'