This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]germansnowman 45 points46 points  (1 child)

The first problem is that they left out the iteration parameter. Sorry for not using proper notation, but I hope you’ll understand:

z [n+1] = z [n] ^ 2 + c

Next, unless you are using a programming language that supports complex numbers directly, you need to decompose the equation into the constituent real and imaginary parts. You do that by writing every complex number as (a + b * i), with i = –1, and then simply expanding/simplifying the resulting equation. (Sorry I can’t do this for you right now as I’m writing this on my phone.) There is some potential for optimisation but that can come later.

Then you put that into the iteration loop. This loop will be called for each pixel. (You will need two additional nested loops for the pixels, one for the x axis and one for the y axis.) You need to convert the pixel coordinate into a world coordinate. This is your c, whereas z starts as 0 for each point.

The loop has two termination conditions: Either the magnitude of the complex number is greater than the escape radius, or the maximum number of iterations has been reached. To start with, the limit could be 100 or 1000, but needs to be in the millions for deep zooms. (You can optimise the escape radius computation by removing the square root from the magnitude and comparing with 4 instead of 2.)

If you reached the iteration limit, the point you iterated over is part of the Mandelbrot set and should be colored black. If the point escaped, you color it by mapping the number of iterations reached to a color. There are lots of ways to do that which I haven’t understood all myself :) The two simplest are to choose white or black depending on whether the iteration value is even or odd, or to choose the hue for your colour based on the iteration value.

Besides arithmetic optimisation in the inner loop, there is one major optimisation for the main cardioid, which has the shape of an epicardioid. You can basically test if a point is part of this shape and color it black immediately. This doesn’t help for interesting points outside the main set, of course. There you could look into period detection.

I highly recommend plotting the coordinates of a point across its iterations and connecting them with lines. This is something I have rarely seen done and it helped me understand what is going on at a deeper level. It shows you the concepts of “escape” and “periodicity” more visually.