Skip to content

Instantly share code, notes, and snippets.

@joaoventura
Created February 15, 2016 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaoventura/c797aefb6188419ab908 to your computer and use it in GitHub Desktop.
Save joaoventura/c797aefb6188419ab908 to your computer and use it in GitHub Desktop.
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.')
plt.show()
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)
anim.save('sierpinski_10000.gif', writer='imagemagick')
plt.show()
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_animation(points)
else:
plot(points)
# 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