public
Created

  • Download Gist
Sierpinski Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
"""
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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.