recursive fractals fractal recursion

Practical Recursion

Fractals

by Robert Deveau 2013


Return to Practical Recursion Home





Fractals

Your browser does not support this page. Get Firefox!
To make the tree on the left, I first drew the tree I wanted to generate on a piece of paper. Then, I came up with the following algorithm:
  1. Draw the trunk
  2. Draw the first V at a given thickness and length
  3. For each point at the top of the V draw another V
  4. With each iteration change the angle, length, and thickness of the V until the smallest V is reached.
  5. Done!

Except that is iteration and not recursion!

Try again
  1. Draw the trunk
  2. Draw the first V at a given thickness and length
  3. But first, draw a V that is smaller, thinner, & angled a little left, on the left side of the first V
  4. But first, draw a V that is smaller, thinner, & angled a little right, on the right side of the first V
  5. Keep increasing the angle, decreasing the thickness and length until I reach the base case where the length is at a certain min (any of: angle, thickness or length could serve as a base case).
  6. Done! *If you want a more realistic tree, you can introduce some randomness into the three mentioned variables.




Now you will need to open up your programming toolbox and turn that algorithm into code. * Probably not as easy as stating the algorithm. Here is what I came up with using javascript and the HTML5 canvas element (some helper functinos included).
I encourage you to try some variations on your own.

Notice Four key sections of code that will be present, in some form, when creating a fractal.

  1. Global variables or Object variables
  2. An initialization function
  3. An update-position function(s)
  4. A draw function(s)

Fractal Generator

The fractal generator below uses a similar set of functions as the tree above to create some common fractals. To use it, select a Fractal and Number of recursive calls from the lists, and click Draw Fractal

All of these fractals have a commonality. Therefore, we can parameterize functions to reflect that.

How to go about writing a similar program

  1. Try changing the number of recursive calls to visualize the repeating patterns.
  2. Write an algorithm for two of the fractals. Compare them, and notice that you can use the same functions to implement similar tasks.
  3. Use iterative programming techniques i.e. agile methods, rapid prototyping. Get one working, then two...
  4. Try different shapes than those listed here.
  5. If you really want to get sophisticated, try color gradients repeating a pattern on a spiral curve :)
Your browser does not support the canvas element. Get Firefox!

Turning a recursive algorithm into code is not the trivial part of understanding recursion, it is the practical part. Like everything else it takes repetition to become good at it.

©2013 deveau enterprises