Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8026

Python • Re: Pi Day

$
0
0
Here is my version from 2013. It uses the Taylor series for arcsin(1/2)=π/6. Each successive term includes an another factor of x²=1/4, so we need log(1/10)/log(1/4)≈1.661 terms per decimal.

Rather than calculating the individual terms and summing them, which would be slow, we use a recursive Binary splitting algorithm to compute a giant quotient equal to the total. It is also important to use gmp (apt install python3-gmpy2) for the multiplications. Python's built-in integers have the necessary range, but they are not implemented efficiently for huge operations.

Code:

from gmpy2 import mpzdef bs(a, b):    if b == a + 1:        if a == 0: return (1, 1, 1)        p = mpz((2*a-1) ** 2)        q = mpz(8*a * (2*a+1))        return (p, q, p)    m = (a+b) // 2    (Pa, Qa, Ta) = bs(a, m)    (Pb, Qb, Tb) = bs(m, b)    return (Pa*Pb, Qa*Qb, Pa*Tb + Qb*Ta)from sys import argvdigits = int(argv[1])(p, q, t) = bs(0, digits * 1661 // 1000 + 9)print(3 * t * mpz(10) ** digits // q)
This will calculate a million digits in 22s on a Pi5. I particularly like that the code is so short, and has seemingly nothing to do with circles.

Statistics: Posted by jojopi — Sun Mar 17, 2024 12:04 pm



Viewing all articles
Browse latest Browse all 8026

Trending Articles