Fibonacci with a memory
how it works
The idea on F(5), then the whole method on F(6), as the watch page runs it.
The Fibonacci numbers start 0, 1, and each later one is the two before it added up: 0, 1, 1, 2, 3, 5, 8. Call them F(0), F(1), F(2) and on, so F(6) is 8. The plain method follows that rule. To work out F(6), it asks for F(5), then F(4), and each of those asks for two more. F(1) and F(0) ask for nothing. It is right, and wasteful: it works the same numbers out again and again. So keep a memo, a list of the answers so far, which the watch page calls the memory. Each time you ask for a number, look in the memo first. If it is there, that is the answer, and you ask for nothing more. If not, work it out and write it in. This page counts calls, one each time a number is asked for, the first included. Sections 2, 3 and 5 name them times asked. A call that has begun and not ended is waiting, and the newest is the one running. The code below, in the language Python, does the same.
- first time
- asked before
- first time
- asked before, answered at once
| number | asked, plain | asked, with a memo |
|---|---|---|
| F(5) | 1 | 1 |
| F(4) | 1 | 1 |
| F(3) | 2 | 2 |
| F(2) | 3 | 2 |
| F(1) | 5 | 2 |
| F(0) | 3 | 1 |
step 1 of 19
Ask for F(6). The memory is empty, so it has to be worked out.
what it remembers to know where it is
- working on
- 6
- answer
- not yet
Where it says not yet, nothing is held there at that moment.
step 6 of 19
To work out F(2), first ask for F(1). It is not in the memory yet.
what it remembers to know where it is
- working on
- 1
- answer
- not yet
Where it says not yet, nothing is held there at that moment.
step 7 of 19
F(1) is 1 by the rule, so write 1 in the memory.
what it remembers to know where it is
- working on
- 1
- answer
- 1
step 9 of 19
F(0) is 0 by the rule, so write 0 in the memory.
what it remembers to know where it is
- working on
- 0
- answer
- 0
step 10 of 19
F(2) is 1 + 0 = 1. Write it in the memory.
what it remembers to know where it is
- working on
- 2
- answer
- 1
step 11 of 19
F(1) is in the memory already: 1. No need to work it out again.
what it remembers to know where it is
- working on
- 1
- answer
- 1
step 12 of 19
F(3) is 1 + 1 = 2. Write it in the memory.
what it remembers to know where it is
- working on
- 3
- answer
- 2
step 19 of 19
Done: F(6) is 8.
what it remembers to know where it is
- working on
- not yet
- answer
- 8
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- ask for F(k): if the memory has it, the answer is therePython lines 9, 10 and 11
- if k is 0 or 1, F(k) is k, so write it in the memoryPython lines 12, 13 and 18
- otherwise ask for F(k - 1), then for F(k - 2)Python lines 14, 15 and 16
- add the two answers, and write F(k) in the memoryPython lines 17 and 18
- F(n) is the answerPython line 21
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def fibonacci_memo(n):
"""Work out F(n), writing each answer down the first time.
F(0) is 0, F(1) is 1, and every later number is the two before it added up.
n is a whole number from 0. Returns F(n).
"""
memo = {} # the answers worked out so far, by k
def ask(k):
if k in memo: # in the memo already, so that is the answer
return memo[k]
if k < 2: # F(0) is 0 and F(1) is 1
answer = k
else:
first = ask(k - 1) # ask for F(k - 1), then for F(k - 2)
second = ask(k - 2)
answer = first + second # add the two answers
memo[k] = answer # write it in the memo
return answer
return ask(n)
how it scales
The plot counts the calls the method makes on F(n), measured from 10 to 100,000.
Each mark across or up is ten times the one before. The line climbs one mark up for each mark across: 199 calls at 100 and 1,999 at 1,000, about 10 times. Here the cost is the calls, and a slope of 1 means it grows as , as section 4's question 1 derives. The plain method is not on this plot: at 100 it would make about 1,146 billion billion calls.
times asked, ten times more at each mark up
, the number asked for, ten times more at each mark to the right
- asking for F(n), the one run there is for that solid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
| times asked | time | |
|---|---|---|
| 1,000 | 1,999 | about 2 microseconds |
| 100,000 | 199,999 | about 200 microseconds |
| 10,000,000 | 19,999,999 | about 20 milliseconds |
The times asked are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count Fibonacci with a memo's calls yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it prints the calls the method
makes and how many of them the memo answers, up to n = 100,000, and the plain
method's calls up to n = 30, where they are still quick to run. The counts are
the same on any computer; only the time differs.
"""
import sys
sys.setrecursionlimit(200_000) # at n = 100,000, 100,000 calls wait, one on another
def fibonacci_memo(n):
"""Work out F(n), writing each answer down the first time.
F(0) is 0, F(1) is 1, and every later number is the two before it added up.
n is a whole number from 0. Returns F(n).
"""
memo = {} # the answers worked out so far, by k
def ask(k):
if k in memo: # in the memo already, so that is the answer
return memo[k]
if k < 2: # F(0) is 0 and F(1) is 1
answer = k
else:
first = ask(k - 1) # ask for F(k - 1), then for F(k - 2)
second = ask(k - 2)
answer = first + second # add the two answers
memo[k] = answer # write it in the memo
return answer
return ask(n)
def counts(n):
"""The same method on n, counting its calls and those the memo answers.
It keeps only which numbers are written, as the calls do not depend on the
numbers, and at n = 100,000 they would fill a lot of memory.
"""
written = set()
calls = 0
answered = 0
def ask(k):
nonlocal calls, answered
calls += 1
if k in written:
answered += 1
return
if k >= 2:
ask(k - 1)
ask(k - 2)
written.add(k)
ask(n)
return calls, answered
def count(n):
"""How many calls the method makes on n."""
return counts(n)[0]
def plain_calls(n):
"""The plain method on n, with no memo, counting its calls."""
calls = 0
def ask(k):
nonlocal calls
calls += 1
if k < 2:
return k
return ask(k - 1) + ask(k - 2)
ask(n)
return calls
if __name__ == "__main__":
print(f"{'n':>6} {'calls':>7} {'answered':>9}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
calls, answered = counts(n)
print(f"{n:>6} {calls:>7} {answered:>9}")
print()
print(f"{'n':>6} {'plain calls':>12} {'with a memo':>12}")
for n in (5, 10, 20, 30):
print(f"{n:>6} {plain_calls(n):>12} {count(n):>12}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here the size is the number you ask for, so each is one input and one run, the same every time. So the table has one column, under the name worst, and no average is worked out.
A case is one kind of input. Here each is one input, so there is one case. A bound says how fast its cost grows as grows.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| worstasking for F(n), the one run there is for that | |
|---|---|
| times asked | , from 1 up |
| answered from the memory | , from 2 up |
| how the times asked grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: From 2 up, a memo of numbers, and at most calls waiting.
Extra memory is the room it needs on top of the input itself, while it runs.
| n | F(n) | calls | worked out | answered | most waiting |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 0 | 1 |
| 1 | 1 | 1 | 1 | 0 | 1 |
| 2 | 1 | 3 | 3 | 0 | 2 |
| 3 | 2 | 5 | 4 | 1 | 3 |
| 4 | 3 | 7 | 5 | 2 | 4 |
| 5 | 5 | 9 | 6 | 3 | 5 |
| 6 | 8 | 11 | 7 | 4 | 6 |
where the formula comes from
Seven questions, each worked line by line. Question 1 is the count the plot draws.
the move: count who asks
the line:- first time
- asked before, answered at once
F(4) with a memo, 7 calls. The solid 4, 3 and 2 each ask for 2. The rest ask for nothing. why it is allowed: The first call counts 1. Every other call is asked for by a call working its number out. F(2) up to F(n) are each worked out once, which is numbers, and each asks for 2. F(1) and F(0) ask for nothing, and nor does a call the memo answers. For 4, 1 + 2 times 3, which is 7.
the move: multiply out
the line:why it is allowed: 2 lots of is 2 lots of , less 2. For 4, 1 + 8 - 2.
guess it, thenthe move: add them up
the line:why it is allowed: 1 less 2 leaves less 1. For 4, 7.
guess it, thenthe move: a ceiling
the line:why it is allowed: Taking 1 away leaves less. For 4, is 7, at most 8.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 2. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: is plus , and from 1 up, is at least 0. For 4, is 7, at least 4.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, only a fixed multiple apart. means both.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: the second ask finds it
the line:worked out first ask second ask F(2) F(1), worked out F(0), worked out F(3) F(2), worked out F(1), answered F(4) F(3), worked out F(2), answered F(5) F(4), worked out F(3), answered F(5)'s run, each number worked out with its two asks, smallest first. why it is allowed: F(k) asks for F(k - 1) first. From 3 up, that call works out F(k - 2) on its way. So when F(k) asks for F(k - 2), the memo holds it.
the move: one for each
the line:why it is allowed: So one answered call for each of F(3) to F(n), which is numbers. Every first ask comes on the first run down, before its number is written, so it is worked out. So is F(2)'s second ask, F(0). For 4, 2.
guess it, thenthe move: the same from question 1
the line:why it is allowed: Every call is worked out or answered. From 2 up, F(0) to F(n) are worked out once each, which is calls. Question 1's less those is . For 4, 7 less 5, which is 2.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the calls
the line:n calls how 0 1 asks for nothing 1 1 asks for nothing 2 3 1 + 1 + 1 3 5 1 + 3 + 1 4 9 1 + 5 + 3 5 15 1 + 9 + 5 6 25 1 + 15 + 9 From 2 up, each row is 1 for its first call, plus the 2 rows just above. why it is allowed: From 2 up, the first call counts 1, and it asks for 2 smaller numbers. Each makes all its own calls, as nothing is written down.
the move: more means more
the line:why it is allowed: F(5) first asks for F(4), so it makes all F(4)'s calls and more, 15 against 9. The same holds from 2 up. 1 and 0 make 1 each.
guess it, thenthe move: leave out the 1
the line:why it is allowed: Line 1, without the first call's 1. For 6, 25 is more than 15 + 9, which is 24.
guess it, thenthe move: swap for the smaller
the line:why it is allowed: By line 2, the calls for are at least those for . For 6, 25 is at least 2 times 9.
guess it, thenthe move: repeat from 0
the line:n m at least counted 0 0 1 1 2 1 2 3 4 2 4 9 6 3 8 25 8 4 16 67 30 15 32,768 2,692,537 The floor doubling, against the calls as counted. why it is allowed: 0 makes 1 call. By line 4, each 2 added at least doubles the calls. An even is 2 added times, so it makes at least 2s multiplied together. Name that .
guess it, thenthe move: what it says
the line:why it is allowed: Line 4 in words, and line 5 is the floor it gives. For 30, is 15, so at least 32,768 calls, and counted, 2,692,537.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: add 1 to each side
the line:why it is allowed: From 2 up, the calls for are 1, for the first call, plus the calls for and for . Add 1 to each side, and the right has one 1 for each bracket. For 6, 25 + 1 is (15 + 1) + (9 + 1).
the move: the rule again
the line:n calls + 1 half of that F(n + 1) 0 2 1 1 1 2 1 1 2 4 2 2 3 6 3 3 4 10 5 5 5 16 8 8 6 26 13 13 Calls plus 1, halved, is the next Fibonacci number. why it is allowed: That is the rule of the Fibonacci numbers themselves. Calls + 1 starts 2, 2, then 4, 6, 10. Halved, that is 1, 1, 2, 3, 5.
guess it, thenthe move: name the place
the line:why it is allowed: At 0 and 1, halved, it gives F(1) and F(2), and each row goes on the same, the Fibonacci number one place on from . For 6, is 7.
guess it, thenthe move: twice that
the line:why it is allowed: Twice F(1) and twice F(2) start it, and each later one adds the two before it, as the Fibonacci numbers do. So it stays twice. For 6, 26 is 2 times 13.
guess it, thenthe move: the calls
the line:why it is allowed: Take the 1 back off. For 6, F(7) is 13, so 25. So the plain method's calls grow as fast as its answers do, as the books say (volume three, chapter 38). Counted, from 20 up, each 1 more multiplies them by about 1.618, as 13,529 calls at 19 become 21,891 at 20.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the promise
the line:why it is allowed: This is what to prove, and lines 2 and 3 prove it. A call writes only at its end, so what it adds was written earlier.
the move: it starts true
the line:why it is allowed: F(1) is 1 and F(0) is 0, by the rule. From 2 up, they come first. A call asks for F(k - 1) first, so the run goes straight down to F(1), and then F(2) asks for F(0).
guess it, thenthe move: one more
the line:written cell number how first 1 1 by the rule second 0 0 by the rule third 2 1 1 + 0 fourth 3 2 1 + 1 fifth 4 3 2 + 1 The memo of F(4), in the order written. Each sum reads two cells already written, so F(2) being right makes F(3) right. why it is allowed: A call on F(k) adds the answers for F(k - 1) and F(k - 2). Each was written before this one, so each is right by the promise so far. By the rule, their sum is F(k). So the promise carries on to each next number.
guess it, thenthe move: a read is as good
the line:why it is allowed: F(k) depends on alone, so asking twice gets one answer. A method that also read today's date could not be kept this way, as the books warn (volume three, chapter 38).
guess it, thenthe move: how many
the line:why it is allowed: F(n) asks all the way down, so from 2 up, each of F(0) to F(n) is written once. For 4, the memo ends 0, 1, 1, 2, 3, which is 5.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: each asks for less
the line:why it is allowed: The watch page stacks every call that has begun and not ended, the newest on top, as section 1's drawings show. Each call above another was asked for by it, for a smaller number. So they go down, with no number twice.
the move: not both 1 and 0
the line:step what happens calls waiting 4 asks for F(1) F4, F3, F2, F1 5 writes F(1) F4, F3, F2 6 asks for F(0) F4, F3, F2, F0 7 writes F(0) F4, F3, F2 8 writes F(2) F4, F3 F(4)'s run at the end of its first run down, the newest last. F0 comes only after F1 has gone. why it is allowed: Only F(2) asks for F(0), and its F(1) has ended by then. F(3)'s ask for F(1) is answered, so it never stands. So at most F(n) down to F(2), and one more.
guess it, thenthe move: the first run down
the line:why it is allowed: That is calls, and the first run down reaches it, F(n) to F(1). For 4, the 4 calls F4, F3, F2 and F1.
guess it, thenthe move: the room they take
the line:why it is allowed: Each call waiting takes room too, to keep its place. Question 5's numbers and these calls are only a ceiling. When the calls are most, the memo holds at most 1 number. For 4, at most 5 + 4, which is 9. On the watch page, filled cells and calls together never pass 5.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: count the steps
the line:F(4) how many looks in the memo 7 additions 3 writes 5 The steps of F(4), 15 in all. why it is allowed: Each call looks in the memo once, question 1's . F(2) to F(n) each add once, additions. F(0) to F(n) are each written once, writes. For 4, 7 + 3 + 5, which is 15.
the move: add them up
the line:why it is allowed: 2 lots of , then , then , make 4 lots of . The rest, less 1, less 1 and plus 1, leave less 1. For 4, 15.
guess it, thenthe move: a ceiling
the line:why it is allowed: Taking 1 away leaves less. For 4, is 15, at most 16.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 4. This is the rule on the page on solving each smaller problem once, at most different problems times a fixed few steps each.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 up, is more than . For 4, is 15, at least 4.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, thenthe move: while the numbers fit
the line:why it is allowed: Many languages keep a whole number in a fixed 64 binary digits, one of them for its sign. F(92) is the last that fits. Python's grow to fit, and an addition takes longer the more digits it adds. F(1000) has 209 ordinary digits. The steps stay as counted, and additions of long numbers cost more.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
count it yourself
F(4), step by step. Each step lists the memo's filled cells in order, as they stand. A call the memo answers adds to both counts on its own step.
| step | the memo | what happens | times asked | answered from the memory |
|---|---|---|---|---|
| 1 | Ask for F(4). The memory is empty, so it has to be worked out. | 1 | 0 | |
| 2 | To work out F(4), first ask for F(3). It is not in the memory yet. | 2 | 0 | |
| 3 | To work out F(3), first ask for F(2). It is not in the memory yet. | 3 | 0 | |
| 4 | To work out F(2), first ask for F(1). It is not in the memory yet. | 4 | 0 | |
| 5 | 1 | F(1) is 1 by the rule, so write 1 in the memory.1 | 4 | 0 |
| 6 | 1 | F(2) also needs F(0), so ask for it next. It is not in the memory yet.1 | 5 | 0 |
| 7 | 0, 1 | F(0) is 0 by the rule, so write 0 in the memory.0, 1 | 5 | 0 |
| 8 | 0, 1, 1 | F(2) is 1 + 0 = 1. Write it in the memory.0, 1, 1 | 5 | 0 |
| 9 | 0, 1, 1 | F(1) is in the memory already: 1. No need to work it out again.0, 1, 1 | 6 | 1 |
| 10 | 0, 1, 1, 2 | F(3) is 1 + 1 = 2. Write it in the memory.0, 1, 1, 2 | 6 | 1 |
| 11 | 0, 1, 1, 2 | F(2) is in the memory already: 1. No need to work it out again.0, 1, 1, 2 | 7 | 2 |
| 12 | 0, 1, 1, 2, 3 | F(4) is 2 + 1 = 3. Write it in the memory.0, 1, 1, 2, 3 | 7 | 2 |
| 13 | 0, 1, 1, 2, 3 | Done: F(4) is 3.0, 1, 1, 2, 3 | 7 | 2 |
In all, 7 times asked. The formula from section 4, , gives at : the same.
where you meet it
Donald Michie named it in the 1960s, and ready-made code offers it now.
Michie's memo functions
Donald Michie described memo functions in Nature in 1968, after a 1967 memorandum: a function that keeps what it has worked out, and looks there first.
source: D. Michie, Memo functions and machine learning (opens in a new tab), Nature 218, his list of publications (opens in a new tab), and the books' volume three, chapter 38
Python's cache
Python's standard library offers this ready-made. Import cache from functools, write @cache above a function, and every answer is kept by what the function was given.
source: the Python documentation, cache in functools (opens in a new tab)
ccache
A compiler turns each file of code into one piece of a program. ccache keeps that piece, filed under a short label, a hash, worked out from the file, the other files it pulls in, the compiler and its options. When that label comes up again, nothing is compiled. Leave one of those out of the hash, and when it changes, a stale answer can come back, as the books warn.
source: the ccache manual (opens in a new tab), and the books' volume three, chapter 38
what is used instead
To fill every number up to anyway, use a table, as section 7 shows: no calls wait. For one far-off number, other methods halve again and again, which this page does not derive.
how it compares
The plain method has no memo. This page's method works top-down, from the big question down. A table has no calls: it fills from the left, and each cell reads the two before it. Keep only the last two numbers, and that is all the memory it needs, though earlier numbers are then gone. A memo suits a problem where many smaller problems are never asked for. From 2 up, every smaller number is asked for here, so a table does as well, with nothing waiting.
| way | work on F(30) | most waiting | numbers kept |
|---|---|---|---|
| plain method | 2,692,537 calls | 30 | none |
| with a memo | 59 calls | 30 | 31 |
| a table | 29 additions | none | 31 |
| a table, the last two only | 29 additions | none | 2 |
| n | calls, plain | calls, with a memo | plain per memo call |
|---|---|---|---|
| 5 | 15 | 9 | 1.7 |
| 10 | 177 | 19 | 9.3 |
| 20 | 21,891 | 39 | 561.3 |
| 30 | 2,692,537 | 59 | 45,636.2 |