Saturday, December 26, 2009

The Mandelbrot Set in JavaScript

JavaScript turns out to be a great language for toying with graphics and visualization. This morning, I spent a few hours learning about the Mandelbrot set and trying to code up a working implementation. The link below is one of the fruits of my labor:

Mandelbrot Set Generator

Mathematically, the Mandelbrot set is the set of points in the complex plane generated by iterating through the formula z = z^2 + c. For different initial values of c, the iteration can either produce a bounded sequence, or tend to infinity. Plotting the graph is a matter of placing a black dot for the values that generate a bounded sequence.



The next part of the problem is figuring out how to test for unbounded sequences. A good approximation can be reached by running through n iterations and quitting if the magnitude of z exceeds 2. The magnitude of a complex number with real part a and imaginary part b is sqrt(a^2 + b^2). For simple graphs, a reasonable value for n is 100.



Here's what a simple Mandelbrot set grapher in JavaScript looks like:
for (var x = 1; x < this.width; x++) {
for (var y = 1; y < this.height; y++) {
var count = 0;
var size = 0;
var cx = xcorner + ((x * zoom) / this.width);
var cy = ycorner + ((y * zoom) / this.height);

var zx = 0;
var zy = 0;

while (count < 100 && size <= 4) {
count += 1;
temp = (zx * zx) - (zy * zy);
zy = (2 * zx * zy) + cy
zx = temp + cx;
size = (zx * zx) + (zy * zy);
}

this.Plot(x, y, count); // count serves as a good color hint.
}
}


By setting the xcorner, ycorner, and zoom variables, the above code allows you to pan across and zoom into various points in the set. To accommodate for pretty visualizations, you can use count to determine the color of the pixel.

A barebones implementation is available here: mandelbrot.js. Although it is not a very efficient implementation, it is very simple, and if you squint hard enough, you can see how the code relates to the visualization.



The Mandelbrot Set Generator is a harness I built with mandelbrot.js. Play with the parameters and let me know if you find anything interesting. It also turns out to be a good browser speed test.

To learn more about the Mandelbrot Set, see the Wikipedia article on the Mandelbrot Set.

2 comments:

  1. I tried to do this in JS too but it killed my browser.

    I think I'll use your .js in my code. (if you dont mind)

    ReplyDelete
  2. I did it in php with html tables. It isnt brilliant, and the html is approx 5mb. All fun and educational games :p

    ReplyDelete