314 Digits of Pi (Python to Clojure)

Pi Day (3/14) is in a couple of days so I want to wish everyone a Happy Pi Day 2020! It's great to see that 55% of American's plan to celebrate and many will be eating pie or pi-themed food (whatever that is).  

My work colleague and basketball buddy Stan sells a nerd t-shirt here: 314 Digits of Pi.py. It has the Python code on the front and the results on the back. I "won" one of these at our annual White Elephant gift exchange in December. Even though the Amazon Best Sellers Rank is #12,306,667 in Clothing, Shoes & Jewelry, I really like it!

I've been staring at the code backward in the mirror for a number of months:

This got me wondering what this algorithm would look like in Clojure?

The first pass on the port was pretty straight forward, but I think it's worth noting some of the subtle differences. All of the code is here: pi-digits.

Here's the original Python code and result:

For the interested, here's an explanation of the calculation of Pi using fixed point math for speed improvements: Pi - Machin: The Machin formula, developed by John Machin in 1706 (!), is:

And here's a Clojure version that returns the identical result:

One problem with the arccot (arc-cotangent) implementation is that it just duplicates the Python logic and is not idiomatic Clojure. Instead of coding this in a non-functional style, i.e. using mutable state (atom), let's create a functional version:

We use loop/recur for a recursive implementation. This has the benefit of tail-call optimization (TCO). Here are the execution times (average of 10 runs) for calculating Pi with the three implementations:

MethodDigits
Time in seconds
10,00050,000100,000200,000
python0.1583.7414.960.3
clojure-while0.2605.1419.878.6
clojure-recur0.2525.1019.878.5

Python is certainly faster, but the purpose here was not to compare computation speed. It was to get a Clojure version of the t-shirt made! Who's the real nerd now? 🙂

This entry was posted in Clojure, Programming and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *