Colouring the Mandelbrot Set is relatively easy, you choose a different colour for each iteration value. This gives the visual effect where the Mandelbrot Set has solid bands of colour, like so:
Now this looks okay, but it’s possible to produce a more aesthetically pleasing image by using an algorithm to produce a smooth gradient, like in this picture:
Comparing the two, the later is definitely preferable! (NOTE: back when these fractals were first being rendered there weren’t computers with 16 million colour palettes, typically restricted to just 16 often garish options, so this kind of smoothing wasn’t feasible)
We achieve this by seeing “how far” the x-y pair is into the colour band, in essence calculating a fractional part for the iteration count. For our Android Wear app we’ve used a algorithm called the “Normalized Iteration Count” which uses the number of iterations to calculate a value between 0 and 1. This value can then be used to interpolate the colours across the band, creating a colour gradient.
The equation to calculate this value is such:
nu = iter - log(log(sqrt(x*x + y*y)/ log(2))/log(2)
The quickest way to grab the fractional part of the value in java is just to cast the double to an int and subtract it from the original value, i.e.
double nu_frac = nu - (int)nu. Now you have a number between 0 and 1 which you can use to interpolate between the colour for the iteration value and the iteration value + 1, like so:
int r = (int)(Color.red(colours[iter]) * (1 - nu_frac) + Color.red(colours[(iter + 1)]) * nu_frac);
int g = (int)(Color.green(colours[iter]) * (1 - nu_frac) + Color.green(colours[(iter + 1)]) * nu_frac);
int b = (int)(Color.blue(colours[iter]) * (1 - nu_frac) + Color.blue(colours[(iter + 1)]) * nu_frac);
That’s all you need to get smooth colouring!