Recurrences: modelling and solving
Model a recursive algorithm or counting problem with a recurrence and solve it by unrolling, substitution with induction, recursion trees, characteristic polynomials, particular solutions and matrix form. The master theorem is deferred to m08.
After this lesson you can
- Model recursive algorithm costs and counting problems with recurrences
- Solve recurrences by unrolling and verify by induction using substitution
- Estimate divide-and-conquer growth using recursion trees
- Solve constant-coefficient linear recurrences including repeated and complex roots
- Compute distant terms in logarithmic time with a companion matrix and fast exponentiation
Before you start
Motivation: sequences defined by themselves
Many quantities important in computing are not known directly, but through how they relate to smaller versions of themselves.
- Recursive algorithm cost. Mergesort sorts elements by sorting two halves and merging with about comparisons. If is cost, code directly says only . “How long?” asks “what function satisfies that equation?”
- Number of size- objects. Binary strings of length without consecutive ones, hallway tilings or legal game positions are counted by decomposing a large object into smaller objects of the same kind. Decomposition relates size- counts to smaller counts.
- Systems evolving in time. An autoregressive model , digital filter or state layer of a model such as S4 or Mamba, , calculates the present from the past. Whether they explode, decay or oscillate depends on a few numbers you will learn to read.
Each case has two tasks. First model: turn an algorithm or counting problem into a precise equation with correct base cases. Second solve: find a closed form or growth order and prove it correct. This lesson covers both with unrolling verified by induction, recursion trees, constant-coefficient linear recurrence theory and matrix form. The general recursion-tree result, the master theorem, belongs to the algorithms module; here we build its intuition and proofs.
Modeling: from an algorithm or count to a recurrence
A recurrence and initial values define a unique sequence: by strong induction, sequences agreeing on and satisfying the same rule agree for every . This also justifies that a terminating recursive function computes something well-defined, the correctness of recursive algorithms from lesson 8. Initial values are part of the recurrence, not a detail: with and with give different sequences. Three models recur throughout the lesson.
Towers of Hanoi
Three pegs and differently sized disks stand on the first, largest to smallest. Move them all to the third one disk at a time, never placing a disk on a smaller one. The recursive solution is nearly forced: to move disks from A to C, move the top from A to B (using C as auxiliary), move the largest A to C, then move the from B to C. If counts moves,
The algorithm taking moves does not show it cannot be improved. A lower bound is needed, and the same recurrence supplies it.
Proof
The algorithm gives . For the reverse show for . Any solution must move the largest disk at least once. Just before its first move, from A to another peg , the remaining disks can be neither on it at A nor on (the largest cannot sit on smaller disks), so they all sit on the third peg: a tower of disks has been transferred, costing at least moves (the largest disk beneath everything neither helps nor hinders). Just after its last move, placing it on C, the disks are all on another peg and must finish atop it: at least another moves. The blocks and largest-disk move are disjoint, so . Since , immediate induction gives .
∎The next figure shows the solution move by move and below it the same recurrence as a strip: each bar has the moved disk’s color. Inspect the strip before unrolling: it is the recurrence drawn.
The strip resembles ruler marks: disk 1 moves on odd-numbered moves, disk 2 on twice an odd number, and generally move uses disk , where counts trailing binary zeros of . This explains why disk moves exactly times.
Strings without consecutive ones
Let count binary strings of length without substring . Classify a valid length- string by last symbol. Ending in , the prefix is any valid string of length , and conversely: strings. Ending in , the penultimate symbol must be , and before the final lies any valid length- string: strings. Cases are disjoint and exhaustive, so the counting principles sum rule gives
This is Fibonacci’s recurrence with different initial conditions: if , . Two modeling details matter. counts the empty string and makes the rule work for : (, , ). The decomposition must be a bijection between length- strings and the disjoint union of lengths and ; if one case could be built in two ways the sum would overcount.
Mergesort cost
Mergesort splits a list into halves of and , recursively sorts each and merges. Merging sorted lists totaling elements costs at most comparisons, attained when both lists are exhausted together. Worst-case comparisons therefore satisfy
This is the exact recurrence. The usual simplifies in two steps: remove floors and ceilings and round the nonrecursive term. Both are reasonable but need justification, supplied below. The implementation cell checks , a closed form not a clean polynomial times because ceilings leave a trace.
Unroll and prove: the substitution method
Unrolling
The most direct way to guess a recurrence solution is repeated application until a pattern emerges. Hanoi:
With , . The figure’s slider shows exactly this: copies of the smaller tower and each sum term a large disk’s moves. For 64 disks, moves: one per second takes roughly 585 000 million years.
For mergesort, when is a power of 2 floors disappear and simplified , with , similarly unrolls:
and gives . Each recursion level contributes and there are levels.
Conjecture and prove
Unrolling convinces, but ellipses hide an induction. Rigorously prove the conjectured formula by induction using the recurrence itself. This combination is unrolling and the substitution method: conjecture a solution form (unrolling, calculating initial terms or analogy), substitute it into the recurrence as induction hypothesis, and adjust constants to close step and bases.
For Hanoi says “.” Base ; if , then . The method is powerful when the exact solution is unknown and only a bound desired: the conjecture has free constant , and proof says which works.
When induction fails: subtract a lower-order term
Consider a recursive traversal splitting a problem in halves and doing constant work per call:
Its binary recursion tree has leaves, suggesting . Try . Assuming the bound for both subproblems,
It fails by , and no fixes that. The conjecture is true (with ), but the hypothesis is too weak to sustain itself: exactly lesson 5’s strengthening the induction hypothesis. Prove something stronger, for some . Now
With the step closes for any , and base requires . Result: , in fact exact (the tree has leaves and internal nodes). The subtracted term gives the hypothesis room to absorb each level’s .
Floors and ceilings
Exact mergesort has floors and ceilings, the solved recurrence did not. Two honest ways bridge the gap.
First, induct directly with floors, as above where kept the calculation exact. With logarithms of , bound in the correct direction; the first guided proof does this for , with the subtlety in choosing base cases rather than the step.
Second, solve at powers of and extend by monotonicity.
Proof
Given , choose with . By monotonicity . Also .
∎Functions , , and satisfy the condition (for , ; hence the theorem starts at , where is positive); does not. Monotonicity of must be proved separately, by strong induction. For : , and for , if for all , then , since each bracket compares equal or consecutive arguments. Thus , between and for , gives for all , not only powers of 2.
Recursion trees
Mergesort’s unrolling has a geometric interpretation: each recursion level costs . A recursion tree makes that explicit for divide-and-conquer recurrences. Each node is a call labeled with work outside recursive calls; children are calls it launches. Total cost is the sum of labels, calculated by levels.
For with and :
- level () has nodes, each of size ;
- each internal node costs , so the level costs ;
- the final level has unit-cost leaves, exactly .
Level costs form a geometric progression with ratio ; everything depends on whether it is below, equal to or above 1.
Proof
The sum counts levels; formally induct on : . Three cases are the geometric series. If , . If , the sum is . If , , and .
∎The theorem gives more than growth: where cost lies. In regime 1 the root alone takes at least fraction of the total, so speedups require cheaper combining. In regime 3 leaves take at least , so fewer subproblems or cheaper bases matter; real Karatsuba and Strassen implementations switch to quadratic or cubic algorithms below a threshold. In regime 2 each level counts.
| Recurrence | Regime | Solution | |
|---|---|---|---|
| Binary search: | equal | ||
| Mergesort: | equal | ||
| Karatsuba: | leaves | ||
| Strassen: | leaves | ||
| root |
Trees also handle asymmetric branches. In , each complete level costs (sizes sum to ), but depths differ: shortest , longest . The first levels are complete and deeper ones not, so total is between roughly and , i.e. . The tree reasons with noninteger and ; rigorous bounds with actual floors use substitution. The master theorem and Akra–Bazzi generalization turn this into general rules including floors, ceilings and non-power terms, in divide and conquer.
Homogeneous linear recurrences
Hanoi, no-consecutive-ones strings and mergesort on powers of 2 share a new term linearly combining earlier ones with coefficients independent of , perhaps plus a constant. This family has a complete theory, also the theory of matrix powers.
The solution space
If and satisfy the recurrence, so does : solutions form vector subspace of sequence space. Mapping to initial values is linear and bijective because initial values determine the sequence and any initial values extend. Thus : finding independent solutions describes all.
Try . Substitute and divide by (if ):
Every characteristic root gives a geometric solution. Since , 0 is not a root. If the roots are distinct we have solutions; repeated roots need more, described next.
Proof
Use shift operator , . Reindexed recurrence says for every , i.e. , and with commuting factors.
They are solutions. For polynomial , , where has degree one less than (or zero for constant ). Applying times to with gives 0, so also annihilates it.
They are independent. Suppose for all with some , and choose such a relation with minimal . Choose index with and apply . The term becomes of lower degree; each term becomes , a polynomial of the same degree as , with leading coefficient multiplied by . The new relation has measure below , so minimality makes all its polynomials zero. This forces for every , leaving for all ; as , vanishes at infinitely many points and is zero. Contradiction.
They form a basis. There are independent solutions in a -dimensional space.
∎Simple roots: Fibonacci and Binet’s formula
For , , with roots and . General solution and initial values give and , so . This is Binet’s formula:
That an expression with always yields integers is no miracle: irrational terms cancel upon binomial expansion. Since , the second term has magnitude below for all , so is the nearest integer to . For no-consecutive-ones strings change initial conditions: .
Repeated roots
If is a double root, the theorem gives and . For example with , has , so . From and we get and . Check .
Where does come from? If roots were and for small , sequence would be a solution, tending as to derivative . When roots merge their geometric solutions become nearly equal, and the normalized difference survives as a new independent solution. Matrix form shows this too: a repeated root is a matrix that cannot be diagonalized.
Complex roots
With real coefficients nonreal roots occur in conjugate pairs and . For a real sequence, coefficients of and are conjugates, and their sum rewrites using Euler’s formula as
Magnitude determines growth and argument oscillation. For , , roots are and solution : period-8 oscillation with amplitude growing like . For roots are of magnitude 1, and every initial sequence has period 6.
Long-term dominance
General form is a sum of terms , and the largest-magnitude root eventually wins.
Proof
Divide the general form by : remaining terms are with , and a polynomial times a geometric term of magnitude ratio below 1 tends to 0. The second part is the same without division: if .
∎For order 2, , everything is visible in coefficient space. Parabola separates real roots (above) from complex roots (below), with a double root on it. Both roots are inside the unit circle exactly in triangle , , : the stationarity region of an AR(2) process in statistics.
Nonhomogeneous recurrences
Hanoi is not homogeneous: has a term that does not depend on previous values. In general we consider
where is a known function of . Solutions have the structure of any linear equation: if is one solution, every other is with a solution of the associated homogeneous recurrence, because the difference of two solutions satisfies the recurrence without . The solutions form an affine space of dimension .
For the encountered in practice, the particular solution is found by undetermined coefficients: propose a form with free coefficients and substitute.
| Term | Form of particular solution |
|---|---|
| polynomial of degree | |
| , with a polynomial of degree |
Here is the multiplicity of as a root of (with in the first row), and if is not a root. The factor is resonance: if the forcing term is already a homogeneous solution, proposing it as it stands gives , so the degree must increase.
The rule is not a magic recipe. If with , the calculation in the previous proof shows that annihilates . Applying to the recurrence, satisfies the homogeneous recurrence with polynomial , in which has multiplicity . By the previous theorem, is a combination of solutions of plus terms with ; those with already solve the original homogeneous recurrence, leaving exactly the form in the table.
The last case explains mergesort again. With and , the recurrence becomes : a change of variable turns divide and conquer into an order-1 linear recurrence with resonance. Its solution, , is , and the of regime 2 in the tree is simply the resonance factor .
Matrix form: the companion matrix
An order- recurrence must remember the last terms. Gather them in a state vector and each step is multiplication by a fixed matrix. For order 2:
All the preceding theory can be read in using what you know about eigenvectors.
- Its eigenvalues are the characteristic roots. Expansion along the first row gives . More directly: if , the vector satisfies , because the first component of is and the rest are the shifted components of . This is the geometric solution seen as a state vector.
- Simple roots are equivalent to diagonalizability. If the roots are distinct, the Vandermonde vectors are independent and . Then , and the last component of is : Binet’s formula is the diagonalization of , and the constants are the coordinates of in the eigenvector basis.
- A repeated root is equivalent to non-diagonalizability. The last rows of are independent (each has a 1 in a different column), so its rank is at least and each eigenvalue has only one eigenvector. A root of multiplicity is then a Jordan block of size , and powers of a Jordan block produce : the polynomial factors in the theorem (you will study these with the Jordan form).
For Fibonacci, and immediate induction gives
Identities follow effortlessly. The determinant gives Cassini’s identity, . And gives the doubling formulas and .
Distant terms in logarithmic time
The matrix form turns “compute ” into “compute ”, and powers are computed with fast exponentiation from lesson 8: square repeatedly and multiply according to the bits of . At most this takes around products of matrices, each with arithmetic operations (naive matrix multiplication), versus for the direct loop.
Two specialist nuances. First, for large integer terms, counting arithmetic operations is misleading: has about bits, and the real cost is dominated by the last multiplications of numbers that size. Even so, exponentiation beats the loop by far: its additions of increasingly long numbers cost bit operations; you will measure this in the implementation. Second, if only is needed (as in cryptography or counting problems with astronomical numbers), fast exponentiation works with bounded numbers and , which has 60 bits of which 24 are 1, takes about 60 squarings and 24 products: fewer than 90 matrix multiplications.
Implementation from scratch
First, the three models from the modelling section checked against brute force: we generate Hanoi moves, enumerate binary strings and count mergesort comparisons on an input constructed to be the worst possible.
from functools import lru_cache
from itertools import product
import math
import numpy as np
def hanoi(n, origen="A", destino="C", aux="B"):
"""Genera los movimientos (disco, de, a) de la solución recursiva."""
if n == 0:
return
yield from hanoi(n - 1, origen, aux, destino)
yield (n, origen, destino)
yield from hanoi(n - 1, aux, destino, origen)
print("Hanói, movimientos generados y 2^n - 1:")
print(" ", [(n, sum(1 for _ in hanoi(n)), 2**n - 1) for n in (1, 4, 8, 12)])
def sin_unos_seguidos(n):
return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))
b = [1, 2]
for n in range(2, 13):
b.append(b[n - 1] + b[n - 2])
print("\ncadenas sin '11', fuerza bruta:", [sin_unos_seguidos(n) for n in range(13)])
print("cadenas sin '11', recurrencia: ", b)
comparaciones = 0
def mergesort(xs):
global comparaciones
if len(xs) <= 1:
return xs
m = len(xs) // 2
izq, der = mergesort(xs[:m]), mergesort(xs[m:])
out, i, j = [], 0, 0
while i < len(izq) and j < len(der):
comparaciones += 1
if izq[i] <= der[j]:
out.append(izq[i]); i += 1
else:
out.append(der[j]); j += 1
return out + izq[i:] + der[j:]
def peor_entrada(xs):
"""Reparte los elementos alternos entre las dos mitades: cada mezcla agota las dos listas a la vez."""
if len(xs) <= 1:
return xs
return peor_entrada(xs[1::2]) + peor_entrada(xs[0::2])
@lru_cache(maxsize=None)
def W(n):
"""Recurrencia exacta del peor caso."""
return 0 if n <= 1 else W((n + 1) // 2) + W(n // 2) + n - 1
rng = np.random.default_rng(0)
print("\n n W(n) peor entrada aleatoria n·ceil(lg n) - 2^ceil(lg n) + 1 n lg n")
for n in [10, 100, 1000, 3000]:
comparaciones = 0
assert mergesort(peor_entrada(list(range(n)))) == list(range(n))
c_peor = comparaciones
comparaciones = 0
mergesort(list(rng.permutation(n)))
L = math.ceil(math.log2(n))
print(f"{n:6d} {W(n):6d} {c_peor:11d} {comparaciones:10d} {n * L - 2**L + 1:20d} {n * math.log2(n):17.0f}")The exact recurrence matches the actual count on the worst input and the closed formula with ceilings, and is a good upper approximation. A random permutation needs only slightly fewer comparisons than the worst case: merging two random lists almost always exhausts one near the end.
Now the three solvers in the lab: direct (and memoized) evaluation, a closed form with numpy.roots roots plus a Vandermonde system for the constants, and powers of the companion matrix with exact integers.
from functools import lru_cache
import numpy as np
def por_iteracion(coefs, iniciales, n):
"""a_n con un bucle: O(k n) operaciones."""
k = len(coefs)
a = list(iniciales)
for m in range(k, n + 1):
a.append(sum(c * a[m - 1 - i] for i, c in enumerate(coefs)))
return a[n]
def memoizada(coefs, iniciales):
"""La recurrencia tal cual, con memoria: cada a_m se calcula una sola vez."""
k = len(coefs)
@lru_cache(maxsize=None)
def a(n):
if n < k:
return iniciales[n]
return sum(c * a(n - 1 - i) for i, c in enumerate(coefs))
return a
def por_raices(coefs, iniciales):
"""Forma cerrada suponiendo raíces simples: a_n = sum_i alpha_i r_i^n."""
k = len(coefs)
r = np.roots([1.0] + [-c for c in coefs]) # raíces de x^k - c1 x^(k-1) - ... - ck
V = np.vander(r, k, increasing=True).T # V[n, i] = r_i^n para n = 0..k-1
alpha = np.linalg.solve(V, np.array(iniciales, dtype=complex))
return r, alpha, np.linalg.cond(V)
def matmul(A, B):
return [[sum(A[i][t] * B[t][j] for t in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
def matpow(M, e):
"""M^e por cuadrados repetidos, con los enteros exactos de Python."""
R = [[int(i == j) for j in range(len(M))] for i in range(len(M))]
while e:
if e & 1:
R = matmul(R, M)
M = matmul(M, M)
e >>= 1
return R
def companera(coefs):
k = len(coefs)
return [list(coefs)] + [[int(j == i) for j in range(k)] for i in range(k - 1)]
def por_matriz(coefs, iniciales, n):
"""a_n es la última componente de C^n x_0, con x_0 = (a_(k-1), ..., a_0)."""
k = len(coefs)
P = matpow(companera(coefs), n)
x0 = list(reversed(iniciales))
return sum(P[k - 1][j] * x0[j] for j in range(k))
casos = {
"Fibonacci": ([1, 1], [0, 1]),
"tribonacci": ([1, 1, 1], [0, 0, 1]),
"par complejo 1 ± i": ([2, -2], [1, 1]),
"raíz doble 3": ([6, -9], [1, 6]),
}
for nombre, (c, ini) in casos.items():
r, alpha, cond = por_raices(c, ini)
print(f"{nombre}: raíces {np.round(r, 4)}, cond(V) = {cond:.1e}")
for n in (12, 40):
exacto = por_iteracion(c, ini, n)
assert exacto == memoizada(c, ini)(n) == por_matriz(c, ini, n)
cerrada = (alpha * r**n).sum()
err = abs(cerrada - exacto) / max(1, abs(exacto))
print(f" n = {n}: exacto {exacto}, forma cerrada {cerrada.real:.10g}, error relativo {err:.1e}")The three approaches agree where they should, with two lessons. The closed form with complex roots returns complex numbers whose imaginary part is rounding noise, even though the sequence is integer-valued. And with the double root, np.roots returns not 3 twice but a conjugate pair , separated by about (on the order of , as expected for a double root): the Vandermonde matrix is nearly singular and the closed form loses half the digits. The “simple roots” solver does not know the correct answer is ; the final code exercise asks you to fix it.
Binet’s formula is exact in mathematics and dangerous in floating point. With float64, has about 16 significant digits, and once has more digits than can be represented, rounding to the nearest integer no longer suffices.
import math, time
def fib_matriz(n):
return matpow([[1, 1], [1, 0]], n)[0][1]
def fib_bucle(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
phi = (1 + math.sqrt(5)) / 2
def fib_binet(n):
return round(phi**n / math.sqrt(5))
primero = next(n for n in range(200) if fib_binet(n) != fib_matriz(n))
print("primer n en que Binet con float64 falla:", primero)
for n in [primero, 100]:
exacto, aprox = fib_matriz(n), fib_binet(n)
print(f" F_{n}: exacto {exacto}\n Binet {aprox} error relativo {abs(aprox - exacto) / exacto:.1e}")
try:
fib_binet(1500)
except OverflowError as e:
print("Binet con n = 1500:", e)
print("\n n bits de F_n bucle (s) matriz (s)")
for n in [25_000, 50_000, 100_000]:
t = time.perf_counter(); x = fib_bucle(n); t_bucle = time.perf_counter() - t
t = time.perf_counter(); y = fib_matriz(n); t_matriz = time.perf_counter() - t
assert x == y
print(f"{n:7d} {x.bit_length():11d} {t_bucle:11.3f} {t_matriz:11.3f}")Binet first fails at , when still fits comfortably in a 64-bit integer: the problem is precision, not the size of the result. The relative error of with which is stored is multiplied by when raised to the th power (because ), and about relative error on is already of order one. From , no longer even fits in a float64. The matrix with exact integers has neither problem. In time, whenever doubles the loop takes about four times as long (there are additions of increasingly long numbers, bit operations in total), and repeated squaring, already an order of magnitude faster at , grows more slowly: Python multiplies big integers with Karatsuba’s algorithm, the recurrence from the tree figure in action, and its cost dominates.
Finally, the recursion tree in numbers: we evaluate exactly on powers of and compare with the prediction for each regime. Also the unbalanced recurrence , which the three-regime theorem does not cover.
import math
import numpy as np
import matplotlib.pyplot as plt
def T_dyv(a, b, c, L):
"""T(b^L) con T(1) = 1 y T(n) = a T(n/b) + n^c, evaluada desde abajo."""
t = 1.0
for j in range(1, L + 1):
t = a * t + float(b**j) ** c
return t
print("recurrencia r T(n)/predicción para n = 2^10, 2^15, 2^20")
for a, b, c, nombre in [(2, 2, 2, "2T(n/2) + n^2"), (2, 2, 1, "2T(n/2) + n"), (3, 2, 1, "3T(n/2) + n"), (7, 2, 2, "7T(n/2) + n^2")]:
r = a / b**c
def pred(n):
if abs(r - 1) < 1e-12:
return n**c * (math.log(n, b) + 1)
return n**c if r < 1 else n ** math.log(a, b)
cocientes = [T_dyv(a, b, c, L) / pred(b**L) for L in (10, 15, 20)]
print(f"{nombre:18s} {r:6.3f} " + " ".join(f"{q:.4f}" for q in cocientes))
from functools import lru_cache
@lru_cache(maxsize=None)
def T_deseq(n):
return 1 if n <= 2 else T_deseq(n // 3) + T_deseq(2 * n // 3) + n
ns = np.unique(np.logspace(1, 6, 60).astype(int))
cociente = [T_deseq(int(n)) / (n * math.log2(n)) for n in ns]
print("\nT(n/3) + T(2n/3) + n, cociente T(n) / (n log2 n) en n = 10^3, 10^4, 10^5, 10^6:",
[round(T_deseq(10**e) / (10**e * math.log2(10**e)), 3) for e in (3, 4, 5, 6)])
print("cotas del árbol: 1/log2(3) =", round(1 / math.log2(3), 3), " 1/log2(3/2) =", round(1 / math.log2(1.5), 3))
plt.semilogx(ns, cociente, "o-", ms=3)
plt.axhline(1 / math.log2(3), color="gray", ls="--", label="rama más corta: 1/log2 3")
plt.axhline(1 / math.log2(1.5), color="gray", ls=":", label="rama más larga: 1/log2(3/2)")
plt.xlabel("n"); plt.ylabel("T(n) / (n log2 n)"); plt.legend(); plt.show()In the root and leaf regimes, the ratio to the prediction stabilizes at a constant, the or from the theorem; in the middle regime it is exactly 1 because the solution is . The unbalanced recurrence stays between the two tree bounds, as expected for .
The library version
| Tool | What it does | Beware |
|---|---|---|
sympy.rsolve(ecuación, a(n), iniciales) | exact closed form of linear recurrences with constant coefficients (and some with polynomial coefficients) | returns complex roots in exponential form, without converting to sines and cosines |
sympy.fibonacci(n), sympy.lucas(n) | exact terms | |
np.roots(coefs) | roots of the characteristic polynomial (eigenvalues of its companion matrix) | repeated roots appear separated by |
np.linalg.matrix_power(C, n) | repeated squaring | int64 integers overflow without warning |
scipy.signal.lfilter(b, a, x) | evaluates in C, very quickly | floating point: inherits the instability of roots with modulus greater than 1 |
import numpy as np
import sympy as sp
from scipy.signal import lfilter
n = sp.symbols("n", integer=True, nonnegative=True)
a = sp.Function("a")
problemas = {
"Hanói": (a(n) - 2*a(n-1) - 1, {a(0): 0}),
"resonancia": (a(n) - 2*a(n-1) - 2**n, {a(0): 1}),
"raíz doble": (a(n) - 6*a(n-1) + 9*a(n-2), {a(0): 1, a(1): 6}),
"par complejo": (a(n) - 2*a(n-1) + 2*a(n-2), {a(0): 1, a(1): 1}),
"Fibonacci": (a(n) - a(n-1) - a(n-2), {a(0): 0, a(1): 1}),
}
for nombre, (ec, ini) in problemas.items():
print(f"{nombre:13s} {sp.factor(sp.rsolve(ec, a(n), ini))}")
# la forma compleja es la oscilación real 2^(n/2) cos(n pi/4)
ec, ini = problemas["par complejo"]
sol = sp.rsolve(ec, a(n), ini)
print("¿igual a 2^(n/2) cos(n pi/4) en n = 0..15?",
all(sp.simplify(sp.expand_complex(sol.subs(n, k)) - 2**sp.Rational(k, 2) * sp.cos(k * sp.pi / 4)) == 0 for k in range(16)))
# matrix_power con int64: F_93 ya no cabe en 64 bits con signo
Q = np.array([[1, 1], [1, 0]], dtype=np.int64)
for k in (92, 93):
print(f"F_{k}: numpy int64 {np.linalg.matrix_power(Q, k)[0, 1]} exacto {sp.fibonacci(k)}")
print("con dtype=object (enteros de Python):", np.linalg.matrix_power(Q.astype(object), 93)[0, 1])
# lfilter: a_n = a_(n-1) + a_(n-2) + x_n, con x = impulso en n = 1 -> Fibonacci en coma flotante
x = np.zeros(80); x[1] = 1.0
F_lfilter = lfilter([1.0], [1.0, -1.0, -1.0], x)
print("lfilter F_79:", int(F_lfilter[79]), " exacto:", sp.fibonacci(79))rsolve reproduces all the lesson’s closed forms, including resonance and the double root. Fibonacci’s appears with and the complex pair’s as , the same real oscillation written with exponentials. Overflow in matrix_power deserves attention: exceeds and NumPy returns a negative number without warning. lfilter is the fast way to evaluate linear recurrences in floating point (it is an IIR filter, the same object under another name), and therefore inherits the limits of float64: is no longer exact.
Common mistakes
Exercises
Step 1 of 4. Why can induction not start at ?
Step 1 of 3. What particular solution should we propose?
solve_linear_recurrence(coefs, iniciales) for , with coefs = [c1, ..., ck] and iniciales = [a0, ..., a(k-1)]. Return a list of tuples (r, m, [alpha_0, ..., alpha_(m-1)]), one per distinct root of multiplicity , such that . The starter code assumes simple roots and fails with repeated roots: group roots that np.roots returns separated by rounding and solve the confluent Vandermonde system, whose columns are . The tests compare your closed form with direct evaluation.import numpy as np
def solve_linear_recurrence(coefs, iniciales):
"""Devuelve [(r, m, [alpha_0, ..., alpha_(m-1)]), ...]."""
k = len(coefs)
r = np.roots([1.0] + [-c for c in coefs])
# versión ingenua: supone que todas las raíces son simples
V = np.vander(r, k, increasing=True).T # V[n, i] = r_i^n
alpha = np.linalg.solve(V, np.array(iniciales, dtype=complex))
return [(r[i], 1, [alpha[i]]) for i in range(k)]Summary
- Modelling requires a bijective decomposition (in counting) or a faithful analysis of the code (in algorithms), and the correct initial values: Hanoi gives , strings without give Fibonacci and mergesort gives .
- Unrolling suggests the solution; the substitution method proves it by induction with explicit constants. If the step fails because of a lower-order term, strengthen the hypothesis by subtracting it. Floors and ceilings are handled in the induction or with monotonicity.
- Recursion trees: in the cost per level is with . If the root dominates, ; if , all levels do, ; if , the leaves dominate, .
- Homogeneous linear recurrences: the general solution is with less than the multiplicity of . Complex roots give , and in the long run the root of greatest modulus dominates.
- Nonhomogeneous: particular plus homogeneous, with the particular solution found by undetermined coefficients and a factor for resonance. Constants are fitted at the end, on the sum.
- Matrix form: with the companion matrix, whose eigenvalues are the characteristic roots. Binet is its diagonalization, repeated roots are Jordan blocks, and by squaring gives distant terms in operations, exact with integers, unlike floating-point Binet.