Sunday, March 6, 2011

Mandelbrot Set












I just finished a trivial but entertaining programming project: rendering a Mandelbrot set using Java.

Mandelbrot sets are named after Benoit Mandelbrot, the recently deceased mathematician that "discovered" them. He took a simple recursive relationship and mapped it onto the complex plane by counting how many iterations were required to observe the magnitude diverge when repeatedly squaring the value at each point:



I've known about Mandelbrot sets for more than twenty years. Chaos theory was all the rage in the late 80s; James Glieck wrote a terrific, accessible book entitled "Chaos: Making A New Science" that summarizes the history beautifully.

Knowing about Mandelbrot sets and having successfully coded them for oneself are two very different things. I saw a question about an implementation on Stack Overflow. Having not gone through it for myself I had nothing to contribute, so I decided to tackle it.

It took me a little while. It all starts with a good Complex class. I implemented the basic arithmetic operators using a fluent style, because it seemed cleaner to me. I wrote a nice JUnit test and asked IntelliJ to tell me about code coverage.

I haven't done any Swing programming in a very long time. I had the set in black and white displaying quickly, but then I had to get a nice color map. It was a happy moment when I saw the picture that accompanies this posting.

That wasn't enough; I had to be able to use the mouse to select a sub-region and zoom in. Once that was working I wanted to be able to save the lovely images to a file. Adding a "save" button would be nice, but my first try just writes the image to an output file when the window closes:



I checked all my code into my local Subversion. I have 100% code coverage for my two model classes (Complex and Mandelbrot, which implements an IterativeFunction iterface) and two view classes (MandelbrotPanel and PixelMapper).

It's not much more than a nice undergraduate problem, but it made me happy to get through it and get such a satisfying result.

I've created an open source project on SourceForge.net and uploaded the code to their Subversion repository. Anyone with a Subversion client can download the code and give it a look:

svn co https://mandelbrotset.svn.sourceforge.net/svnroot/mandelbrotset mandelbrotset


profile for duffymo at Stack Overflow, Q&A for professional and enthusiast programmers