Here’s a short snippet that draws the Hilbert space-filling curve using a recursive approach.

It sounds counterintuitive. A curve normally has no area, it’s just a line. But a space-filling curve is a special type of curve that gets arbitrarily close to every point in a 2D square. If you keep refining it, the curve passes so densely through the space that it effectively covers the entire square. In the mathematical limit, it touches every point.

The idea was first made concrete by Giuseppe Peano in 1890, who described the first such curve. A year later, David Hilbert introduced a simpler and more structured version, now known as the Hilbert curve. It’s built from repeating U-shaped patterns that fit together in a recursive way.

One interesting property is that the curve is continuous. There are no jumps. Despite that, the curve eventually reaches every location in the square. It’s not smooth, it has no derivative anywhere, but it’s fully connected and fills space in a precise way.

Beyond theory, these curves have practical uses. The Hilbert curve preserves locality, meaning nearby points on the curve often remain close together in the 2D plane. That makes it useful for things like image compression, memory layout, and database indexing.

import numpy as np
import matplotlib.pyplot as plt

def hilbert(level=5, x=0, y=0, xi=1, xj=0, yi=0, yj=1):
    if level <= 0:
        return np.array([[x + (xi + yi)/2, y + (xj + yj)/2]])
    else:
        return np.vstack([
            hilbert(level-1, x,           y,           yi/2, yj/2,  xi/2,  xj/2),
            hilbert(level-1, x+xi/2,      y+xj/2 ,     xi/2, xj/2,  yi/2,  yj/2),
            hilbert(level-1, x+xi/2+yi/2, y+xj/2+yj/2, xi/2, xj/2,  yi/2,  yj/2),
            hilbert(level-1, x+xi/2+yi,   y+xj/2+yj,  -yi/2,-yj/2, -xi/2, -xj/2)
        ])

level = 6
coords = hilbert(level)

# Plotting
fig, ax = plt.subplots(1, 1, figsize=(6, 6))
ax.plot(coords[:,0], coords[:,1], 'k-', lw=(5/level)**.5)
ax.set_title("Hilbert curve")
ax.set_aspect('equal')
ax.axis('off')
plt.show()