# Fun with fractals

May 13, 2016 · 3 mins read

# The Mandelbrot Set

Just for fun, I tried to create a shader in glslsandbox where I visualise the Mandelbrot set.

This is how it looks: Source code here.

The implementation is fairly simple.

Wikipedia defines the Mandelbrot set as “the set of complex numbers c for which the function f_c(z)=z^2+c does not diverge when iterated from z=0” All this means is that: – We have a function: f_c(z)=z^2+c -> input: a complex number -> output: another complex number

Choose any complex number and call this function recursively (using the output as input for the next call). If the number eventually grows to infinity, it is not a member of of the Mandelbrot set. If it does NOT grow to infinity, then it is a member of the Mandelbrot set.

When can we decide whether a number will grow to infinity or not? -> If the absolute value of the complex number gets greater than 2.

How can this help me create beautiful images?

Remember how any complex number can be positioned in the complex plane? In this plane the x-axis represents the “real” part, and the y-axis represents the “imaginary” part of the number. Imagine that we put our screen inside this plane. First we need to define some boundaries for the axis.I choose an x-axis from -2 to 1 and a y-axis form -1 to 1. Then for each pixel we find the corresponding complex number (x + yi) and use the above formula to find out if it is a part of the Mandelbrot set. If it is, we simply colour it black. (picture from wikipedia) Where are all the nice colours?

We can get a more colourful visualisation by changing the colour of all numbers that are not in the set, depending on how many iterations we needed to find out that it diverged.

I did this: col.r = iterations / maxIterations ## Some math

As mentioned earlier, this is the function we need to evaluate: $$f_c(z)=z^2+c$$

First of all, how do we represent a complex number? -> Simple: Create a structure that has two float values: one representing the real part and one representing the imaginary part

In our function we need to add complex numbers. -> Simply add the the real parts and the imaginary parts of both numbers. $$c = a + b$$

=>

$$c.real = a.real + b.real$$

$$c.im = a.im + b.im$$

We also need to square a complex number. We can represent a complex number as (a+bi), where a is the real part and b is the imaginary part. We then multiply it by itself. Remember that $$i=\sqrt{-1}$$

$$((a+bi)^2 = (a+bi)*(a+bi) = a^2 + 2abi + (bi)^2 = a^2 + 2abi - b^2)$$

So the real part becomes: $$(a^2 - b^2)$$

and the imaginary part: $$(2ab)$$

Finally, we need to calculate the absolute value of the complex number, to see if it diverges.

$$(|c| = \sqrt{a^2+b^2})$$

## What’s next?

• You can change the function used 