Skip to main content

Medium fractals · complex numbers · shaders

The Mandelbrot set

Square a number, add a constant, repeat. Some points never get away.

Write mandelbrot(x, y, size). It is called for every pixel of a size by size canvas, x running right and y running down from 0 at the top left. Return a brightness from 0 to 1.

Map the pixel to a point c = cr + ci·i on the complex plane: cr = -2 + 3 * x / size and ci = -1.5 + 3 * y / size. So the canvas covers -2 to 1 across and -1.5 to 1.5 down.

Start with z = 0 (zr = 0, zi = 0) and a counter n = 0. While n < 32 and zr * zr + zi * zi <= 4, replace z with z squared plus c (new zr = zr * zr - zi * zi + cr, new zi = 2 * zr * zi + ci, both from the old values) and add 1 to n. Return n / 32. Points that never escape return 1 and are the set itself.

Example: the pixel (0, 48) on a 96 canvas maps to c = -2. z goes 0, -2, 2, 2, 2 and never passes 4, so mandelbrot(0, 48, 96) returns 1. The top left corner c = -2 - 1.5i escapes after one step and returns 1 / 32 = 0.03125.

Tests you can see

  • mandelbrot(0, 48, 96)1
  • mandelbrot(0, 0, 96)0.03125
  • mandelbrot(64, 48, 96)1

More tests are hidden. The server runs them all before a time counts.

Run your code and this canvas paints itself.

javascriptmandelbrot()

Tab indents · Cmd/Ctrl+Enter runs