Application: Solving Recurrences
A linear recurrence such as the Fibonacci rule defines each term from the previous few. Packing the last few terms into a vector turns the rule into one matrix multiplication per step. Eigenvalues then give a closed formula for the -th term, and fast matrix powers give an exact algorithm.
A recurrence is a matrix power
Keep the two most recent Fibonacci numbers in a vector. One step of the rule is a fixed matrix :
Taking steps is the matrix power , and in fact . Everything from Application: Matrix Powers now applies.
Binet's formula from the eigenvalues
The characteristic polynomial of is (trace 1, determinant −1), with roots
Each eigenvalue has eigenvector , since and for these roots. The starting vector splits as
Since , the term shrinks to nothing, so is the integer closest to , and the ratio tends to , the golden ratio. SymPy confirms the algebra exactly:
from sympy import Matrix, sqrt, simplify, expand, fibonacci
Q = Matrix([[1, 1], [1, 0]])
print("eigenvalues:", list(Q.eigenvals()))
phi, psi = (1 + sqrt(5)) / 2, (1 - sqrt(5)) / 2
binet = [simplify(expand((phi**n - psi**n) / sqrt(5))) for n in range(11)]
print("Binet n=0..10:", binet)
print("matches fibonacci():", binet == [fibonacci(n) for n in range(11)])
print("Q^10 =", (Q**10).tolist())eigenvalues: [1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
Binet n=0..10: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
matches fibonacci(): True
Q^10 = [[89, 55], [55, 34]]
Two programs: exact powers vs. floating point
Binet's formula looks like an algorithm, but it needs to full precision. With 64-bit floats it breaks once has more digits than a double can hold. Raising to the -th power by repeated squaring needs only about small matrix products and Python's exact integers, so it works for any . This is the same "square and multiply" idea as fast modular exponentiation, and an alternative to the loop or memoised recursion of Dynamic Programming.
import math
def mat_mult(X, Y):
return [[X[0][0] * Y[0][0] + X[0][1] * Y[1][0], X[0][0] * Y[0][1] + X[0][1] * Y[1][1]],
[X[1][0] * Y[0][0] + X[1][1] * Y[1][0], X[1][0] * Y[0][1] + X[1][1] * Y[1][1]]]
def fib(n): # Q^n by repeated squaring: O(log n) products
result, base = [[1, 0], [0, 1]], [[1, 1], [1, 0]]
while n:
if n & 1:
result = mat_mult(result, base)
base = mat_mult(base, base)
n >>= 1
return result[0][1] # Q^n = [[F(n+1), F(n)], [F(n), F(n-1)]]
phi = (1 + math.sqrt(5)) / 2
first_bad = next(n for n in range(200) if round(phi**n / math.sqrt(5)) != fib(n))
print("float Binet first wrong at n =", first_bad)
print("F(71) exact:", fib(71), " float:", round(phi**71 / math.sqrt(5)))
print("F(300) has", len(str(fib(300))), "digits")float Binet first wrong at n = 71
F(71) exact: 308061521170129 float: 308061521170130
F(300) has 63 digits
General two-term recurrences
The same method solves for any constants. The step matrix is the companion matrix , whose characteristic polynomial is . So:
| Roots of | General solution |
|---|---|
| two distinct roots | |
| one repeated root |
The constants come from and . The repeated-root case is exactly when the companion matrix is not diagonalizable, which is where the extra factor comes from.
Example: with , . The roots of are 2 and 3, so with and , giving , :
SymPy's rsolve does the same automatically:
from sympy import Function, rsolve, symbols
n = symbols("n", integer=True)
a = Function("a")
sol = rsolve(a(n) - 5 * a(n - 1) + 6 * a(n - 2), a(n), {a(0): 1, a(1): 4})
print("a(n) =", sol)
print([sol.subs(n, i) for i in range(6)])a(n) = -2**n + 2*3**n
[1, 4, 14, 46, 146, 454]
In software
- Algorithm analysis: the running time of divide-and-conquer or dynamic-programming code is often a linear recurrence; the largest root of its characteristic polynomial gives the growth rate.
- Counting: the number of binary strings without two consecutive 1s, of tilings of a strip, or of paths in a state machine all satisfy linear recurrences, and matrix powers count them for huge (modulo a prime in competitive programming).
- Signal processing: an IIR filter is a linear recurrence; it is stable exactly when both roots satisfy .
- Random number generators: linear congruential and xorshift generators are linear recurrences, the latter over (Fields).
Exercises
Exercise 1: A Fibonacci cousin
Solve with , .
Answer
, giving
Solution
Exercise 2: Lucas numbers
The Lucas numbers follow the Fibonacci rule but start , . Show that .
Answer
().
Solution
Exercise 3: A repeated root
Solve with , .
Answer
.
Solution
Exercise 4: Tribonacci by matrix power
The tribonacci numbers satisfy with , , . Write the step matrix, compute with a matrix power, and compare with the matrix's largest eigenvalue.
Answer
Step matrix ; ; both the ratio and the dominant eigenvalue are .
Solution
The state vector is , and the first row adds the three entries. Starting from , is the first entry of . SymPy matrices use exact integers:
import numpy as np
from sympy import Matrix
M = Matrix([[1, 1, 1], [1, 0, 0], [0, 1, 0]])
state = M**48 * Matrix([1, 0, 0]) # (T50, T49, T48)
T50, T49 = state[0], state[1]
print("T50 =", T50)
print("T50/T49 =", round(float(T50 / T49), 6))
lam = max(abs(np.linalg.eigvals(np.array(M.tolist(), dtype=float))))
print("largest eigenvalue =", round(float(lam), 6))T50 = 3122171529233
T50/T49 = 1.839287
largest eigenvalue = 1.839287
Test yourself
Which matrix advances the Fibonacci state to ?
Why is the integer nearest to ?
- Because is rational
- Because , so is always smaller than in size
- Because is an integer
- It is only true for even
How many matrix multiplications does repeated squaring need for ?
- About
- About
- About
- Exactly 1