Calculate Pi quickly

Home | Blogs

Calculating PI with a computer is actually really fast and easy to code. Using the Chudnovsky algorithm is the best algorithm currently available to compute pi.

The algorithm is this:

1/pi = 12 * sima q = 0, goes to infinity of ((-1)^q*(6q)!*(545140134q+13591409))/((3q)!*(q!)^3*(640320)^(3q+3/2))

We can simplify this down to:

pi = c*(sigma q = 0, goes to infinity of (M_q*L_q)/(X_q))

C = 426880*sqrt(10005)

Changing with QQ = 0
L_(q+1) = L_q + 545140134L_0 = 13591409
X_(q+1) = X_q * (-2625374126440768000)X_0 = 1
K_(q+1) = K_q + 12K_0 = -6
M_(q+1) = M_q * (k_(q+1)^3 - 16*K_(q+1))/(q+1)^3   M_0 = 1

If you want to try and implement this, you have to make sure that you are either using a library that can handle infinity-sized numbers or your language can.

You will want to first make a variable for each variable above and set it to its q = 0 state.

Once you have the initial values, you can make a variable for the sigma and set it to M*L/X.

Just make a loop (that will eventually finish if you want it to ever stop calculating) and take L and add 545140134 to itself, X and times -2625374126440768000 to itself, and K add 12 to itself. With Q, you have to multiply (K^3-16k)/(q+1)^3 to itself.

We calculated K before M for the reason of not having to worry about K_(q+1).

Once you are done with your loop, just do 426880*sqrt(10005)*/(sigma). Doing the divide can be hard to calculate, so you can just do the reciprocal and time it, and you will get the same value. This will end with pi.

When q = 0, you already get 13 digits, and calculating just the first number is really quick, but sadly the time complexity is O(n(log n)^3) so it gets really slow after a while.

If you want to try and multithread this function, you can only put one sigma calculation in a new thread, as all the rest will be used in the next sigma calculation.

The actual calculation is easy to code, and I found some rust code that does the calculation with a few lines of code if you want to try and make your own and need a reference: oniani/chudnovsky.

Go calculate Pi in whatever language you want!