Level: Beginner → Intermediate
You’ll learn: How the Mandelbrot set works, pixel-by-pixel image generation, fast NumPy loops, and exporting an animated GIF.
The Mandelbrot set is the set of complex numbers c for which the sequencez₀ = 0
, zₙ₊₁ = zₙ² + c
does not escape to infinity. We color each pixel by how fast it escapes (iteration count).
from PIL import Image
import numpy as np
W, H = 800, 600
max_iter = 200
# Plot window (classic view)
RE_START, RE_END = -2.5, 1.0
IM_START, IM_END = -1.2, 1.2
# Create coordinate grid
re = np.linspace(RE_START, RE_END, W)
im = np.linspace(IM_START, IM_END, H)
C = re[np.newaxis, :] + 1j*im[:, np.newaxis]
Z = np.zeros_like(C)
it = np.zeros(C.shape, dtype=np.int32)
for i in range(max_iter):
# Where still inside the radius-2 circle, iterate
mask = np.less(np.abs(Z), 2.0)
Z[mask] = Z[mask] * Z[mask] + C[mask]
it[mask & (np.abs(Z) >= 2.0)] = i
# Simple color mapping
norm = it / it.max()
img = (255 * np.dstack([
0.5 + 0.5*np.sin(6.28*(norm + 0.00)),
0.5 + 0.5*np.sin(6.28*(norm + 0.33)),
0.5 + 0.5*np.sin(6.28*(norm + 0.66)),
])).astype("uint8")
Image.fromarray(img).save("mandelbrot.png")
print("Saved mandelbrot.png")
What the code does (high level):
C
) matching image pixels.Z = Z² + C
while tracking the escape iteration in it
.