When reading John Derbyshire’s excellent book Prime Obsession, I stumbled upon the following interesting footnote about Euler’s number:

“*Here is an example of e turning up unexpectedly. Select a random number between 0 and 1. Now select another and add it to the first. Keep doing this, piling on random numbers. How many random numbers, on average, do you need to make the total greater than 1? Answer: 2.71828…*”

Personally I found this rather intriguing, so I decided to try this out for myself. Clojure seemed to be an obvious choice for this, since it’s very easy to express ones thoughts in code.

Let’s start with a function that will tell us how many random numbers we needed to sum up to get over 1:

Next we will create a function that will take n elements from an infinite list generated from another function:

We are doing this because def-ing a seq will cache it:

Now we have to find out how many numbers it takes on average to go over 1:

Let’s wrap it all up and also display the results as floats:

Sure enough, the results seem to be around the value of e, curiosity satisfied. Last but not least the final program in all its glory:

Note: this will die with an OOM error when you try to calculate the average of a too long list. Fixing this is left as an exercise for the reader (“holding on to the head” will probably be useful as a search term).