© 2018 - Analytics Link

A simple Fractal Tree using recursion in Python

November 1, 2018

I'd been looking into recursion as a way of hard-coding a recursive partitioning tree (rather than using an inbuilt package from Python or R) and during my search came across Fractal Trees which are drawn using recursive logic.

 

Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.  In coding, this essentially means calling a function from within that very same function.  For a really good insight into this, and a run-through an example of how you can calculate the factorial value using recursion, I recommend watching the below video on the subject from Computerphile:

 

 

To get started on drawing a fractal tree, I wanted something simple and easy.  I found some explanations and code here which are perfect.

 

To draw the tree, we're using turtle which is a graphics module within Python (it comes standard in all versions)

 

import turtle

 

def tree(branchLen,t):
    if branchLen > 10:
        t.forward(branchLen)
        t.right(40)
        tree(branchLen-30,t)
        t.left(80)
        tree(branchLen-30,t)
        t.right(40)
        t.backward(branchLen)

 

def main():
    myWin = turtle.Screen()
    myWin.bgcolor("black")
    t = turtle.Turtle()    
    t.width(10)
    t.left(90)
    t.up()
    t.backward(100)
    t.down()
    t.color("silver")
    tree(150,t)
    myWin.exitonclick()

 

main()

 

In the main() function, we set up the turtle 'canvas', draw the trunk, and then call the tree() function for the first time.

Within the tree() function, we draw each extra branch and then recursively call the tree function again and again from within, each time providing a slightly smaller branch length back to the function.

 

The result is below:

 

 

I'm pretty happy with this for a first attempt - I'm now going to go and play around with the different inputs and try and make something more complex!

 

 

 

Share on Facebook
Please reload

Please reload

Recent Posts