math

Visualizing the Mandelbrot Set

fractalsvisualizationpython

The Mandelbrot set is defined by iterating:

[ z_{n+1} = z_n^2 + c ]

where (c) is a point on the complex plane and (z_0 = 0). If the sequence stays bounded, (c) belongs to the set.

Python Implementation

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot(h, w, max_iter=256):
    y, x = np.ogrid[-1.4:1.4:h*1j, -2:0.8:w*1j]
    c = x + y*1j
    z = 0
    divtime = max_iter + np.zeros(z.shape, dtype=int)

    for i in range(max_iter):
        z = z**2 + c
        diverge = abs(z) > 2
        div_now = diverge & (divtime == max_iter)
        divtime[div_now] = i
        z[diverge] = 2

    return divtime

plt.imshow(mandelbrot(400, 600), cmap="twilight")
plt.axis("off")
plt.savefig("mandelbrot.png", dpi=150)

The result is a 400×600 slice of the boundary — the edge where order dissolves into infinity.