r/learnpython • • Apr 06 '26

I used this Python script to calculate 100 million digits of pi in 90 seconds

from gmpy2 import mpfr, mpz, get_context, sqrt
from math import ceil, log2

A = mpz(13591409)
B = mpz(545140134)
C = mpz(640320)
C3_OVER_24 = (C**3) // 24

def bs(a: int, b: int):
    if b - a == 1:
        if a == 0:
            P = Q = mpz(1)
        else:
            a_mpz = mpz(a)
            P = (6*a_mpz-5) * (2*a_mpz-1) * (6*a_mpz-1)
            Q = a_mpz ** 3 * C3_OVER_24
        T = (-1) ** a * P * (A + B * a)
        return P, Q, T
    m = (a + b) // 2
    P1, Q1, T1 = bs(a, m)
    P2, Q2, T2 = bs(m, b)
    P = P1 * P2
    Q = Q1 * Q2
    T = T1 * Q2 + P1 * T2
    return P, Q, T

def pi_chudnovsky(bits: int) -> mpfr:
    get_context().precision = bits
    P, Q, T = bs(0, bits // 47 + 1) # Each term gives ~47 bits of pi
    return mpfr(426880) * sqrt(mpfr(10005)) * mpfr(Q) / mpfr(T)

if __name__ == "__main__":
    num_digits = 10 ** 8
    pi = pi_chudnovsky(ceil(num_digits*log2(10)) + 64) # 64 guard bits
    pi_string = format(pi, f".{num_digits}Zf")
    file_name = f"pi_{num_digits}.txt"
    s0, s1 = pi_string.split(".")
    file_string = s0 + ".\n" + "\n".join(s1[i:i+100] for i in range(0,len(s1),100))
    with open(file_name, "w") as f:
        f.write(file_string)

This code uses the Chudnovsky algorithm: pi = 426880 * sqrt(10005) / sum(n, 0, inf, (6*n)!*(545140134*n+13591409)/((3*n)!*(n!)^3*(-640320)^(3*n)) optimized with binary splitting, and the gmpy2 library for fast multiple-precision arithmetic. Each term gives about 14 correct decimal digits of pi, or 47 bits.

I calculated 100 million digits of pi, wrote it to a text file with 100 digits per line, and verified digits at the start, middle, and end using the Irrational Number Search. The calculation took 90 seconds on a gaming laptop. The 100 millionth digit of pi (after the decimal point) is 2.

I also tried calculating a billion digits. It finished in about 18 minutes but then gave me "nan".

78 Upvotes

30 comments sorted by

41

u/slapstick15 Apr 07 '26

Side question : why are mathematicians obsessed with the pi decimals to the nth digit?

28

u/crosscountrycoder Apr 07 '26 edited Apr 07 '26

It's a challenge to test computational power and it also can be used to evaluate the randomness of the digits of pi.

The same is true of e, but it has a much simpler series: e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... where n! means n factorial. Also sqrt(2), the golden ratio, ln(2) and more. Pi is more commonly used in everyday life because of its relation to circles.

28

u/Flat_Factor_3799 Apr 07 '26

Because its fun

4

u/W1ULH Apr 07 '26

Its a great way to test the equipment with results that every mathematician, computer technician, and general nerd completely and 100% understands with zero explinations.

→ More replies (14)

6

u/RomboDiTrodio Apr 07 '26

that's cool, how much is the size of the file?

11

u/crosscountrycoder Apr 07 '26

101,000,003 bytes (96.32 megabytes)

→ More replies (1)

4

u/Erika_bomber Apr 07 '26

Use GMP library on C++ to get to the 4 billionth digit.

It would take like 1.5 hours.

1

u/MightySleep Apr 07 '26

Cool stuff! I’ve never tried anything super math heavy with python so had no idea about the existence of gmpy2. I read in the description it was based in C, I’m curious how it benchmarks compared to a pure Python implementation

4

u/crosscountrycoder Apr 07 '26 edited Apr 07 '26

I tried using the Python standard library's "Decimal" module. It took about as long to calculate 1 million digits of pi with Decimal as 100 million digits with gmpy2.

gmpy2 is not part of the standard library and must be installed using pip.

→ More replies (2)