Search code examples
pythonrecursionturtle-graphicsfractals

Drawing fractals using recursion


Recently i started learning about recursion and i noticed there is something called fractals , i made simple tree with it.

But i have a problem with getting the recursion idea of this fractal https://i.sstatic.net/7Pap4.png

i saw something like it but made with squares.

Can any one explain the recursion idea for this one ? I tried this algorithm with Python(turtle)

def fractal(start,length,direction,t):

    if(length < 10):

       return

    t.rt(direction)

    direction = int(direction/360) # To make it only {90,-90}

    t.fd(length)

    fractal(start+length,length/2,direction+90,t)

    fractal(start+length,length/2,direction-90,t)

    t.lt(direction)

    fractal(start+length,length/2,direction+90,t)

    fractal(start+length,length/2,direction-90,t)

Solution

  • The basic shape of the fractal is a large letter "H" with smaller versions of itself at each of its four tips. So what you basically have to do is draw an "H" in turtle, and whenever you are at the tips, call fractal again with half the length. Keep in mind that the turtle should always be oriented in the same direction when the function starts, and has to return to the origin after drawing the shape. The function could look somewhat like this:

    def fractal(length, t):
        if length >= 10 :
            # draw left side 
            t.lt(90)
            t.fd(length)
            t.rt(90)
            t.fd(length)
            fractal(length//2, t)
            t.bk(length*2)
            fractal(length//2, t)
            t.fd(length)
            # draw right side
            t.rt(90)
            t.fd(length*2)
            t.lt(90)
            t.fd(length)
            fractal(length//2, t)
            t.bk(length*2)
            fractal(length//2, t)
            t.fd(length)
            # back to origin
            t.lt(90)
            t.fd(length)
            t.rt(90)
    

    You could also use that fact that both sides of te figure are symmetrical:

    def fractal(length, t):
        if length >= 10:
            t.rt(90)
            side(length, t)
            t.rt(180)
            side(length, t)
            t.rt(90)
    
    def side(length, t):
        t.fd(length)
        t.rt(90)
        t.fd(length)
        fractal(length//2, t)
        t.bk(length*2)
        fractal(length//2, t)
        t.fd(length)
        t.lt(90)
        t.bk(length)