Lesson 27: Fractal tree
A tree made of trees
- Look at a real tree: each branch looks like a small tree, and its branches look like even smaller trees.
- A shape that is made of smaller copies of itself is a fractal.
- To draw it, write a function that calls itself: draw the trunk, then draw two smaller trees on top.
Words for this lesson
| Word | Meaning |
|---|---|
| fractal | a shape made of smaller copies of itself |
| recursion | a function that calls itself |
| base case | when the function stops calling itself |
| depth | how many levels are left |
How the calls grow
| depth | trunk length | branches at this level |
|---|---|---|
| 4 | 400 mm | 1 |
| 3 | 240 mm | 2 |
| 2 | 144 mm | 4 |
| 1 | 86 mm | 8 |
| 0 | stop | – |
- Each call makes two calls, so the number of branches doubles at each level.
A smaller example
from vexcode_vr import *
def count_down(n):
if n == 0:
brain.print("Go!")
return
brain.print(n)
brain.new_line()
count_down(n - 1)
def main():
count_down(3)
vr_thread(main)
- The brain shows 3, 2, 1 and then
Go!.n == 0is the base case: without it the calls would never stop.
In the exam (A-Level 9618)
Recursion is in A-Level Computer Science (9618), not in IGCSE 0478.
- 9618/31/M/J/23 Q12(a): describe what is meant by recursion. The mark scheme's points, in your tree:
- a function that is defined in terms of itself:
treecallstree; - a base case that returns without a recursive call:
if depth == 0: return; - a general case where the recursive call happens:
tree(length * 0.6, depth - 1), which moves towards the base case.
- a function that is defined in terms of itself:
الصعوبة 5/5 · 400 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Draw a tree with a function that calls itself. tree(length, depth) draws the trunk, then two smaller trees on top of it: turn left 30°, call tree(length * 0.6, depth - 1), turn right 60°, call it again, turn left 30°, and drive back down the trunk. When depth is 0 it stops. Draw tree(400, 4). The robot must end at the bottom of the trunk, facing up.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 5/5 · 400 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Make it a bigger tree, tree(400, 5), with leaves: the last, smallest branches (depth 1) are green and all the others are black. Set the pen colour at the start of tree, and again before driving back down, because the smaller trees changed it.
اضغط تشغيل لرؤية المخرجات هنا.