Skip to content
scipython.com

P7.5.1The Chaos Game

The so-called chaos game is an algorithm for generating a fractal. First define the \(n\) vertices of a regular polygon and an initial point, \((x_0,y_0)\), selected at random within the polygon. Then generate a sequence of points, starting with \((x_0, y_0)\), where each point is a fraction \(r\) of the distance between the previous one and a polygon vertex chosen at random.

Write a program to draw fractals using the chaos game algorithm and test it with values \(n=3, r=0.5\).

Show solution

Experiment with the code below to produce different-looking fractals. Note that not all combinations of (n,r) produce fractals, however.

The algorithm applied with parameters \(n=3, r=0.5\) generates a Sierpinski triangle.

chaosgame
import numpy as np
import matplotlib.pyplot as plt

image_size = np.array((300, 300))
r, nsides, npts = 0.5, 3, 50000

# The vertices of a regular polygon with nsides sides and a vertex pointing up,
# calculated on the unit circle centered at (1,1)
polygon = [
    (np.cos(phi) + 1, np.sin(phi) + 1)
    for phi in np.arange(0, 2 * np.pi, 2.0 * np.pi / nsides)
]
# Map vertices to image pixels
pts = np.array(polygon) * 0.5 * (image_size - 1)
# Initial point at centre of polygon
p1 = np.array(image_size / 2)
aimg = np.zeros(image_size)

# Play the Chaos Game!
for i in range(npts):
    irow = np.random.randint(nsides)
    p2 = pts[irow]
    p1 = p1 * r + p2 * (1 - r)
    aimg[tuple(p1.astype(int))] += 1

fig, ax = plt.subplots()
ax.pcolor(aimg)
ax.set_ylim(100, 300)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

plt.show()
Sierpinski triangle created by the Chaos Game algorithm
Sierpinski triangle created by the Chaos Game algorithm.