Linear Recurrences
Fibonacci numbers, the number of ways to tile a strip, the population of a model ecosystem and the cost of some recursive programs all satisfy linear recurrences with constant coefficients:
There is a complete recipe for solving them, based on the roots of a polynomial. (In matrix language this is diagonalization; see Recurrences in the linear algebra course.)
Homogeneous recurrences ()
Try . Substituting and dividing by gives the characteristic equation
- If its roots are distinct, the general solution is .
- A root of multiplicity contributes .
- The constants come from the initial values (a linear system).
Fibonacci. gives , roots and . With , : and , so , giving Binet's formula again (Generating Functions). Since , is the integer nearest to .
SymPy's rsolve follows this recipe:
from sympy import Function, rsolve, symbols, simplify
n = symbols("n", integer=True)
f = Function("f")
fib = rsolve(f(n) - f(n - 1) - f(n - 2), f(n), {f(0): 0, f(1): 1})
print("Fibonacci:", fib)
print([simplify(fib.subs(n, k)) for k in range(10)])
rep = rsolve(f(n) - 4 * f(n - 1) + 4 * f(n - 2), f(n), {f(0): 1, f(1): 4})
print("repeated root r = 2:", rep)Fibonacci: -sqrt(5)*(1/2 - sqrt(5)/2)**n/5 + sqrt(5)*(1/2 + sqrt(5)/2)**n/5
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
repeated root r = 2: 2**n + 2*2**(n - 1)*n
The second recurrence has , a double root, so its solution has the form .
Tiling a strip
How many ways can a strip be tiled with dominoes? The leftmost column is either one vertical domino (leaving ) or two horizontal dominoes stacked (leaving ):
Fibonacci again, shifted: . Many counting problems reduce to a linear recurrence once you split on what happens at one end.
from functools import lru_cache
@lru_cache(None)
def tilings(n):
if n <= 1:
return 1
return tilings(n - 1) + tilings(n - 2)
def brute(n):
"""Count tilings of a 2 x n strip by placing dominoes cell by cell."""
def go(filled):
if all(filled.values()):
return 1
c, r = min((c, r) for (r, c), v in filled.items() if not v) # leftmost empty cell
total = 0
for cells in ([(r, c), (r + 1, c)], [(r, c), (r, c + 1)]):
if all(filled.get(x) is False for x in cells):
for x in cells:
filled[x] = True
total += go(filled)
for x in cells:
filled[x] = False
return total
return go({(r, c): False for r in range(2) for c in range(n)})
print([tilings(n) for n in range(1, 11)])
print([brute(n) for n in range(1, 11)])[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Inhomogeneous recurrences
If : find one particular solution by guessing a function of the same shape as (constant, polynomial, exponential), then add the general homogeneous solution, and fit the constants to the initial values.
Example. , (Towers of Hanoi). Homogeneous part: . Particular: try a constant : gives . So , and gives : .
If the guess has the same shape as a homogeneous solution (e.g. with root 2), multiply the guess by .
In software
Linear recurrences describe running times ( for naive Fibonacci is ), loan balances, digital filters (IIR filters are linear recurrences on signals) and random number generators (linear congruential and linear-feedback shift registers). They can be evaluated in steps with matrix powers by repeated squaring.
Exercises
Exercise 1: Distinct roots
Solve , , .
Answer
.
Solution
, so . Then and , giving .
Exercise 2: Particular solution
Solve , .
Answer
.
Solution
Particular constant: , so . General: ; gives . Check: .
Exercise 3: Bit strings without "11" (code)
Count binary strings of length with no two consecutive 1s. Find the recurrence and check it by brute force.
Answer
with , , so .
Solution
A valid string ends in 0 (any valid string of length before it) or in 01 (any valid string of length before it).
from itertools import product
brute = [sum(1 for s in product("01", repeat=n) if "11" not in "".join(s)) for n in range(1, 13)]
b = [2, 3]
while len(b) < 12:
b.append(b[-1] + b[-2])
print(brute)
print(b)[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Test yourself
What is the characteristic equation of ?
A double root contributes which terms to the general solution?
- only
- and
- and
How many ways can a strip be tiled with dominoes?
- 5
- 8
- 13
- 10