Monday, July 12, 2010

Curious? Factor to the rescue!

A lot of dynamic language users have strong interest in math (particularly those who use functional programming languages). Some months back I came across a fun blog post about using Clojure to approximate Euler's Number, according to this observation:

"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..."

I wanted to contrast his solution with one using Factor. We'll use these vocabularies:

USING:kernelmathrandomsequences;

We can use the random vocabulary to create a random float between 0 and 1, counting how many numbers we need to add before the value is greater than 1:

This could be improved by virtualizing the sequences and then performing an incremental average as we generate each of n approximations. That would likely result in both memory and speed improvements (although I haven't tried it yet).

2 comments:

Just for fun I wrote it in... Clojure! My first Clojure program aside from the hello world test.

I wanted to do it in Common Lisp (or Forth, but Factor is too similar, better something new), but when I fired slime under emacs, I realised I had it configured for Clojure. I'll post it in my blog tomorrow, probably.