Calculating Pi with Swift by@Alex_Wulff

Calculating Pi with Swift

Alex Wulff HackerNoon profile picture

Alex Wulff

22-Year-Old Maker and Harvard Student

Back in November of 2016, researchers managed to calculate pi to 22.4 trillion digits. This was done using something called the Chudnovsky Algorithm, which looks a little something like this:

Printing out all these digits at a reasonable font size would require a modest 139 miles of stacked paper.

Of course, 22 trillion digits is about 22 trillion digits more than necessary for any application. NASA only uses around 15, and 40 can calculate the circumference of the known universe with a precision of the width of a hydrogen atom. Not bad.

What’s good enough for NASA is good enough for me, so I decided to have my program find pi to the 15th decimal place (3.141592653589793).

The Chudnovsky Algorithm scares me with all of those factorials and exponents — I wanted something easier to program. I first turned to a nicer-looking (and much more inefficient) infinite series: the Leibniz formula. Here’s what it looks like:

Doubles in Swift generally have a precision of 15 decimal places, which is perfect for my application. In a few minutes, I whipped up the following Swift program in Playgrounds:

I left the program to run while I went to grab breakfast, thinking it wouldn’t take more than a few minutes. I came back to find my computer turning itself into a space heater while still working on the 6th decimal place. This was only around the 200,000th iteration of the while loop.

I should’ve heeded the warning that this is one of the more inefficient ways of computing digits of pi.

If someone reading this has access to a really powerful computer I’d love to see how far you can get before the whole system becomes sluggish.

Next I turned to the slightly more efficient Nilakantha series:

After spending a few minutes getting Xcode respond (it was still working its way through Leibniz formula), I was eventually able to develop this:

Learning from my last trial, this time I expected to wait for hours. Much to my surprise the program finished at 31958 iterations before I was done checking my code for errors. Not bad!

Clearly, Swift (and Swift Playgrounds) is not the best language to implement processor-intensive tasks. Lower-level languages such as C++ are better suited. However, I do find it interesting to see how implementations of these various formulas differ from system to system.

A great resource for playing with the more efficient algorithms can be found here. As you can see, the Chudnovsky algorithm can get 14 digits in one iteration, even if there’s way more math involved per run.

Give these Swift programs a try on your own system and tell me your results!

To see more of my writing, follow me and check out my page on Medium.


Signup or Login to Join the Discussion


Related Stories