Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sierpinski Triangle (with the animations)
Creates the Sierpinski triangle using the Chaos Game technique.
Starts from a vertex of a triangle, chooses randomly the next vertex and
draw a pixel in the middle. Then, iteratively selects a new vertex and
draws in the middle point.
import random
import matplotlib.pyplot as plt
from matplotlib import animation
def plot(points):
Plots the points using matplotlib.
Points is a list of (x, y) pairs.
xx = [x for (x, y) in points]
yy = [y for (x, y) in points]
plt.plot(xx, yy, 'g.')
def do_animation(points):
Plots an animation of zooming using matplotlib.
Points is a list of (x, y) pairs.
xx = [x for (x, y) in points]
yy = [y for (x, y) in points]
fig = plt.figure()
def init():
ax = plt.axes(xlim=(0, 1), ylim=(0, 1))
return ax.plot(xx, yy, 'g.')
def animate(i):
scale = 1 - i * 0.02
ax = plt.axes(xlim=(0, scale), ylim=(0, scale))
return ax.plot(xx, yy, 'g.')
anim = animation.FuncAnimation(
fig, animate, init_func=init, frames=50, interval=200, blit=False)'sierpinski_10000.gif', writer='imagemagick')
def sierpinski(n, animate=False):
Generates positions for the Chaos Game Sierpinski
triangle with 'n' iterations in a square of size 1x1.
vertices = [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)]
points = []
# initial vertex
x, y = random.choice(vertices)
for i in range(n):
# select new vertex
vx, vy = random.choice(vertices)
# get middle point
x = (vx + x) / 2.0
y = (vy + y) / 2.0
points.append((x, y))
if animate:
# Do the triangle with 10.000 points and no animations
sierpinski(n=10000, animate=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.