Mandelbrot sets are complex numbers which don't diverge when iterated as starting from .
Wait, you said no math?
That's all, and you don't need to understand it. Forget I said the above. Take a
2D plane, each point has an x
and y
coordinate,
right?
Okay, so we start a loop with u, v
set to 0, 0
for
each pixel x, y
and keep applying the following function:
function step([u, v], [x, y]) {
return [u * u - v * v + x, 2 * u * v + y]
}
At each step, we'll get a new u, v
. If these don't grow beyond
2, 2
after a few hundred iterations, then x, y
is part
of the Mandlebrot set, and we plot it. That's it.
If you're curious, here is how we derive the programmatic statement from the mathematical one (you don't need to understand this to draw mandelbrot sets!)
To recap, the Mandelbrot set contains to find which
The only complex operations we need are addition and multiplication. We don't
need a complex number library, we can just express
as a two component array [u, v]
. Then the complex multiplication
(squaring) becomes:
Giving us [u * u - v * v, 2 * u * v]
. To this we add
, similarly expressed as a two component array [x,
y]
to give us the step
function above.
That's really it. There is more to it of course, but that usually has to do with the medium in which you are rendering the Mandelbrot set (scaling the coordinates appropriately, zooming into an region of interest, implementing it efficiently etc).
As a concrete example, here is the JavaScript function I'm using to draw the Mandelbrot sets here.
const mbExit = ([x, y]) => {
let u = 0, v = 0
for (let i = 1; i <= 100; i++) {
const nu = u * u - v * v + x
const nv = 2 * u * v + y
u = nu
v = nv
if (Math.abs(u) > 2 || Math.abs(v) > 2)
return i
}
return 0
}
The step function has been inlined for efficiently, and an arbitrary iteration count has been picked. I'm not sure if the exit conditions are mathematically correct, but for the level of precision that I needed, they seem to work.
This mbExit
function returns the iteration count at which a given
diverges, or 0
if it is part of the
Mandelbrot set.
Armed with this function, I can draw Mandelbrot sets anywhere. The above example uses 80 x 24 HTML divs, but the same function also works for the much higher resolution HTML canvas illustrations that I'd made to show the fractal nature of truth.