How to Animate Recursion: A Fun and Visual Guide — Discovering Fractals

How to Animate Recursion: A Fun and Visual Guide — Discovering Fractals

·

6 min read

Recursion is one of those concepts that can be hard to grasp at first, but once you get it, it can open up a whole new world of possibilities. Recursion is when a function calls itself, either directly or indirectly, to solve a smaller version of the same problem. Recursion can be used to solve many problems in mathematics, computer science, logic, linguistics, and more.

Photo by Martin Rancourt on Unsplash

But how can we visualize recursion? How can we see what is happening behind the scenes when a recursive function is executed? How can we make recursion more fun and engaging?

One way to do that is to use animations. Animations can help us understand how recursion works by showing us the steps of the recursive process, the changes in the data structures, and the flow of control. Animations can also make recursion more appealing and entertaining by adding some colors, shapes, and movements.

In this article, we will explore some examples of animations using recursion, and learn how to create our own animations with some simple tools and techniques. Let’s get started!

Example 1: Recursive Power Function

The first example we will look at is a recursive power function. This function takes two parameters: a base x and an exponent n, and returns x raised to the power of n. For example, pow(2, 3) returns 8.

The recursive definition of this function is:

  • If n is 1, return x
  • Otherwise, return x times pow(x, n-1)

This means that to calculate x^n, we need to multiply x by itself n times. We can do this by calling the same function with a smaller exponent until we reach the base case of n = 1.

Here is a possible animation of this function:

In this animation, each node represents a recursive function call. The height of the tree is the depth of the call stack (n). The value of each node is the result of that function call. The animation shows how the function calls itself with smaller exponents until it reaches the base case, and then returns the results back up the tree by multiplying them with x.

To create this animation, we can use a tool called Recursion Visualization Tool, which allows us to enter a recursive function in Java and see its execution as a tree. We can also customize the appearance of the nodes and edges, and export the animation as a GIF.

Here is the code for the recursive power function in Java:

int pow(int x, int n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n-1);
}
}

And here are some settings for the Recursion Visualization Tool:

  • Node shape: circle
  • Node color: blue
  • Node size: 20
  • Edge color: black
  • Edge width: 2
  • Animation speed: 0.5

We can then enter pow(2, 3) as the input and see the animation.

Example 2: Recursive Fibonacci Calculation

The second example we will look at is a recursive Fibonacci calculation. The Fibonacci sequence is a series of numbers where each number is the sum of the previous two numbers. The first two numbers are 1 and 1. For example, the first 10 Fibonacci numbers are:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

The recursive definition of this sequence is:

  • If n is 0 or 1, return n
  • Otherwise, return fib(n-1) + fib(n-2)

This means that to calculate the nth Fibonacci number, we need to add the previous two Fibonacci numbers. We can do this by calling the same function with smaller indices until we reach the base case of n = 0 or n = 1.

Here is a possible animation of this function:

In this animation, each node represents a recursive function call. The height of the tree is the depth of the call stack (n). The value of each node is the result of that function call. The animation shows how the function calls itself with smaller indices until it reaches the base case, and then returns the results back up the tree by adding them.

To create this animation, we can use the same tool as before, Recursion Visualization Tool, and enter the following code for the recursive Fibonacci function in Java:

int fib(int n) {
if (n <= 1) {
return n;
} else {
return fib(n-1) + fib(n-2);
}
}

And here are some settings for the Recursion Visualization Tool:

  • Node shape: circle
  • Node color: green
  • Node size: 20
  • Edge color: black
  • Edge width: 2
  • Animation speed: 0.5

We can then enter fib(5) as the input and see the animation.

Example 3: Recursive Tree Animation

The third example we will look at is a recursive tree animation. This is a more creative and artistic example of using recursion to generate a complex and beautiful pattern. A recursive tree is a tree where each branch splits into two or more smaller branches, and this process repeats until a certain condition is met.

Here is a possible animation of a recursive tree:

In this animation, each branch represents a recursive function call. The length and angle of each branch are determined by some parameters that change with each level of recursion. The animation shows how the function calls itself with different parameters until it reaches a minimum branch length, and then stops.

To create this animation, we can use a tool called Processing, which is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. Processing allows us to create graphics and animations with simple code.

Here is the code for the recursive tree animation in Processing:

// Define some constants
final float ANGLE = radians(25); // The angle between branches
final float LENGTH_FACTOR = 0.7; // The factor by which branch length decreases
final float MIN_LENGTH = 4; // The minimum branch length

void setup() {
size(600, 600); // Set the window size
background(255); // Set the background color to white
}

void draw() {
translate(width/2, height); // Move the origin to the bottom center of the window
stroke(0); // Set the stroke color to black
branch(200); // Draw the first branch with length 200
}

void branch(float len) {
line(0, 0, 0, -len); // Draw a line from the origin to len pixels above
translate(0, -len); // Move the origin to the end of the line

if (len > MIN_LENGTH) { // Check if we need to stop recursing
pushMatrix(); // Save the current transformation matrix
rotate(ANGLE); // Rotate by ANGLE radians to the right
branch(len * LENGTH_FACTOR); // Draw a smaller branch to the right
popMatrix(); // Restore the previous transformation matrix

pushMatrix(); // Save the current transformation matrix
rotate(-ANGLE); // Rotate by ANGLE radians to the left
branch(len * LENGTH_FACTOR); // Draw a smaller branch to the left
popMatrix(); // Restore the previous transformation matrix
}
}

And here are some settings for Processing:

  • Sketch > Present: Run the sketch in full-screen mode
  • File > Export Application: Export the sketch as an executable application

We can then run or export the sketch and see the animation.

Conclusion

In this article, we have seen some examples of animations using recursion, and learned how to create our own animations with some simple tools and techniques. We have also learned some basic concepts of recursion, such as recursive definition, base case, recursive case, call stack, and time complexity.

Recursion is a powerful technique that can help us solve complex problems with elegant code. However, recursion can also be challenging to understand and debug. Animations can help us visualize recursion and make it more fun and engaging.

I hope you enjoyed this article and learned something new. If you have any questions or feedback, please let me know in the comments below. Thank you for reading!