c=circle((1,0),5) # arguments are center, radius
# Returns a Graphics object
plot(c) # Graphics objects can be plotted
c2 = circle((-1,-1), 3)
plot(c+c2) # You can add Graphics objects together and plot them
tri = polygon([(0,0), (1,1), (2,1)]) # returns a filled in polygon
plot(tri)
quad = polygon([(0,0), (1,1), (2,1), (3,0)]) # a quadrilateral
plot(quad)
# Now we will try to draw a Sierpinski triangle
# code for 0th iteration
equi_tri = polygon([(0,0), (1,0), (1/2, sqrt(3)/2)])
plot(equi_tri)
# Code for a single equilateral triangle
def tri(basept, size):
"""Return an equilateral triangle with left vertex at
basept (x,y)
and given size."""
(x,y) = basept
return polygon([(0+x,0+y), (size*1+x,0+y), \
(size*(1/2)+x, size*sqrt(3)/2 +y)])
tri((1,0), 0.7)
# code for 1st iteration
t1 = tri((0,0), 1/2)
t2 = tri((1/2,0), 1/2)
t3 = tri((1/4,sqrt(3)/4), 1/2)
plot(t1+t2+t3)
# code for nth iteration
def sierp_tri(basept, size, iter):
"""Draw sierpinski triangle of given size, number of
iterations, with left vertex at basept. Use recursion."""
# graphic = Graphics() # makes an empty graphics object
# will add triangles to this to get final sierp tri
if iter == 0:
return tri(basept, size)
else:
# copy the code for 1st iteration, but replace
# each triangle with a sierp_tri with iter-1 iterations
(x,y) = basept
t1 = sierp_tri(basept, size/2, iter-1)
t2 = sierp_tri((x+size/2,y), size/2, iter-1)
t3 = sierp_tri((x+size*1/4, y+size*sqrt(3)/4), size/2, iter-1)
return t1 + t2 + t3
sierp_tri((0,0), 1, 5)
sierp_tri((0,0), 1, 6).save("sierp_tri_6.pdf")
# saves graphics object as a pdf file