Skip to content

Instantly share code, notes, and snippets.

@trinath
Created December 18, 2010 11:04
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 trinath/746409 to your computer and use it in GitHub Desktop.
Save trinath/746409 to your computer and use it in GitHub Desktop.
"""
Implement the sierpenskis triangle by using the recuresive algorithm of removing a triangle step by step
"""
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import math
def triangle(vertices,ax):
"""
Take the arguments of vertices (np.array) and axis object and gives out triangle
formed with midpoints and returns vertices of midpoints
"""
l=[]
l.append((vertices[0]+vertices[1])/2)
l.append((vertices[1]+vertices[2])/2)
l.append((vertices[0]+vertices[2])/2)
ax.add_patch(patches.Polygon(l,fill=True,facecolor='w'))
return l
def sierper(verts,ax,count=0):
"""
Gives out a serper with the vertices given
"""
if count==7:
return
count=count+1
vertices=triangle(verts,ax)
list1=np.array([[0,0,2],[1,0,1],[2,1,2]])
for i in range(3):
temp_array=np.array([verts[list1[i,0]],vertices[list1[i,1]],vertices[list1[i,2]]])
sierper(temp_array,ax,count)
def main():
fig = plt.figure()
ax = fig.add_subplot(111)
verts = np.array([[0.0, 1.0], [-math.sqrt(3)/2, -0.5], [math.sqrt(3)/2, -0.5]])
poly = patches.Polygon(verts,facecolor='k',fill=True)
ax.add_patch(poly)
ax.set_xlim(verts[:,0].min()-0.1,verts[:,0].max()+0.1)
ax.set_ylim(verts[:,1].min()-0.1,verts[:,1].max()+0.1)
sierper(verts,ax)
plt.show()
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment