Experiment with the code below to produce different-looking fractals. Note that not all combinations of (n,r)
produce fractals, however.
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.*np.pi/nsides)]
# Map vertices to image pixels
pts = (np.array(polygon) * 0.5 * (image_size-1)).astype(np.int)
# Initial point at centre of polygon
p1 = np.array(image_size/2, dtype=np.int)
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)] += 1
plt.pcolor(aimg)
plt.show()
The algorithm applied with parameters $n=3, r=0.5$ generates a Sierpinski triangle.