Generating functions and analytic combinatorics
Generating functions turn counting problems into algebra on power series. Study ordinary and exponential generating functions, Catalan, Stirling and Bell numbers, integer partitions, the Flajolet-Sedgewick symbolic method, and asymptotics from the dominant singularity.
After this lesson you can
- Translate combinatorial constructions such as sums, products, sequences, and sets into generating-function equations.
- Choose between ordinary and exponential generating functions for unlabelled and labelled objects.
- Derive formulas for Catalan, Stirling numbers of the second kind, Bell numbers, and integer partitions.
- Find the asymptotic growth of a sequence from the dominant singularity of its generating function.
- Implement arithmetic on truncated series and check coefficients against enumeration.
Before you start
Motivation: an infinite sequence in one equation
How many ways can you tile a strip of with squares and dominoes? The last piece is either a square or a domino, so the number satisfies with : Fibonacci, a linear recurrence solved in the previous lesson using its characteristic polynomial. Now change the question: how many binary trees have nodes? A nonempty tree is a root with a left subtree of nodes and a right subtree of , so
This recurrence is not linear with constant coefficients: each term depends on all preceding terms, multiplied together. No characteristic polynomial will solve it. Yet the answer is as clean as .
The tool that finds it is an idea of Abraham de Moivre (1730) and Euler that looks like a trick but turns out to be a language: package the whole sequence into a power series, . The sum of products is exactly the coefficient of in , and the entire recurrence, including its initial condition, becomes a single quadratic equation:
One algebraic equation encodes infinitely many numbers. From it we will obtain both the exact formula and the growth, , read from the geometry of in the complex plane.
Why does this matter if you want to build models and systems?
- Analysis of algorithms. The average number of quicksort comparisons, the average height of a search tree, and the cost of a hash table can be calculated by solving recurrences with generating functions (as in randomized quicksort). They are central to average-case analysis.
- Probability. The probability generating function applies the same idea to a distribution: the generating function of a sum of independent variables is the product of their generating functions, just as for products of classes here.
- Search spaces. The number of ways to parenthesize a product of matrices (the contraction order of a
einsum) is . Expressions and syntax trees of a given size, and configurations of a grammar, can all be counted this way; their growth tells us whether exhaustive search is feasible. - Formal languages and neural networks. Balanced parentheses, the Dyck language, are a classic test of a sequence model’s ability to follow hierarchical structure (Hahn, 2020); counting valid strings of each length is a generating-function question.
We start with formal series, the algebra that makes all this rigorous without discussing convergence; then ordinary generating functions and Catalan numbers; exponential generating functions for labelled objects (Stirling numbers, Bell numbers, and derangements); integer partitions; the symbolic method that unifies them; and finally how the singularity closest to the origin determines growth.
Formal power series
In analysis, a power series is a function defined where it converges. Here we use a more modest and robust object: a sequence with a convenient notation.
The product is the convolution familiar from multiplying polynomials. The observation that makes everything work is that each coefficient of the result is a finite sum: uses only and . There are no limits, no convergence, and no to evaluate. With these operations is a commutative ring: associativity and distributivity are inherited coefficient by coefficient from polynomials. Here is just a placeholder.
That is why , which converges at no , is a perfectly legitimate member of : it can be added, multiplied, and, as we will see, inverted.
Proof
If , the constant term gives , hence . Conversely, if , the equality is the infinite system and for . Solving for from the term of the -th equation gives the stated recursion, determining each from . There is exactly one solution.
∎The fundamental example is the geometric series: , so in
By contrast, has no inverse: is not a power series but a Laurent series, which allows negative exponents. If a manipulation leads you to divide by something with no constant term, first factor out and check that it cancels.
Composition. If , the composition is well defined: starts at degree , so for the coefficient of only terms contribute, again a finite sum. If , it is not generally well defined: the constant term of would be , an infinite sum that is not even rational.
Formal derivative. , defined coefficient by coefficient. It obeys the product and chain rules, which are polynomial identities in the coefficients, and will let us translate multiplication by .
The coefficients need not be rational or integer, but in combinatorics they almost always are. A useful detail: if and all are integers, the inverse recursion divides only by , so the inverse has integer coefficients. That is why produces integers and the implementation below can use exact Python integers.
Ordinary generating functions
The second expression is the important one: each object contributes a monomial , and grouping by size gives the coefficients. The dictionary between operations on series and on sequences is short and worth keeping handy:
| Series | Coefficient | Use |
|---|---|---|
| disjoint union of classes | ||
| (0 if ) | shift indices | |
| pairs of objects whose sizes add | ||
| partial sums | ||
| multiply by | ||
| choose with repetition |
The last row is the generalized binomial theorem, , or, without formulas, the stars and bars argument: chooses an exponent in each of the factors, and counts solutions of with .
Solving recurrences
The method always has three steps: multiply the recurrence by and sum over the for which it holds; rewrite each sum using the generating function, incorporating the initial conditions; then solve and extract coefficients, usually using partial fractions.
Notice that the nonhomogeneous term required no guess at a “particular solution”: it enters the equation as another series, , whose double root at produces the term . The previous lesson’s method required guessing the form of a particular solution; this one computes it.
This example is a special case of a theorem connecting this lesson with the previous one.
Proof
Calculate . Its coefficient of degree is (with if ). The recurrence says exactly that these coefficients vanish for , so is a polynomial of degree less than . Since , is invertible in and . The converse reads the same calculation backward. For the last claim, .
∎The partial-fraction solution of and the characteristic-polynomial solution are therefore the same: if , then , and each fraction contributes , a polynomial in times , as in the preceding lesson. The companion matrix is a third face of the same object: its eigenvalues are the .
Counting compositions
A composition of is an ordered sequence of positive integers summing to : . Here the generating function appears without any recurrence. If the allowed parts have generating function , with the number of distinct parts of size and , then a composition with exactly parts is an element of the Cartesian product of copies of the set of parts, with size equal to the sum of their sizes. By the product rule applied size by size, these compositions have generating function , and summing over gives
Strips of squares and dominoes are compositions with parts , , and their generating function is : Fibonacci, without writing the recurrence. With all positive parts, and , whose coefficient is for : each of the gaps between cells is either cut or left uncut.
The interactive previews the symbolic method: the same collection of pieces yields very different sequences depending on the constructor. The final readout, the ratio , approaches , where is the smallest positive root of , the point where blows up. This is our first glimpse of the idea in the lesson’s final section.
Catalan numbers
Return to binary trees. By inductive definition, a binary tree is either the empty tree or a root with an ordered pair of binary trees (left and right). Its size is the number of nodes.
The equation translates the inductive definition term by term: “empty” contributes , one object of size 0; “root with two subtrees” contributes for the root times for the left subtree times for the right, because the product of generating functions counts pairs whose sizes add. Solving for in a quadratic equation in has two subtleties: choosing the sign of the root and justifying that is a formal series. Both, along with coefficient extraction, are covered by the first guided proof exercise at the end. Here we prove the formula for by another, purely combinatorial route, to see both perspectives.
Four faces of the same number
First, why does appear everywhere? There are explicit bijections among many families.
- Dyck paths of semilength : sequences of up steps and down steps that never go below the axis.
- Balanced parentheses with pairs: the same object, writing as “(” and as “)”.
- Binary trees with nodes.
- Triangulations of a convex polygon with sides using noncrossing diagonals.
The bijection between paths and trees is the first-return decomposition. A nonempty Dyck path starts with ; let be the step that first returns it to the axis. Between that and lies a Dyck path shifted up by one, followed by another, :
Applying the same decomposition recursively builds the whole tree, pairing each node with a matching pair. In the polygon, number vertices from to and use side as the base. The triangle on the base has a third vertex ; its left and right subpolygons are the triangulations of the subtrees. The four families satisfy the same equation for the same reason, which gives the bijections.
Notice two things in the figure. First, with the root selected, the “objects with this split” readout is the summand in the recurrence; stepping through the objects traverses the entire sum, block by block. Second, flipping a polygon diagonal is a tree rotation, the operation used to rebalance AVL and red-black trees. The graph of triangulations joined by flips is the skeleton of a polytope, the associahedron; rotation distance between binary trees is a classical data-structures problem.
The reflection formula
Proof
There are paths from to with up steps and down steps. The bad paths touch the line . Given a bad path, reflect the segment from the origin to its first contact with that line across . The new path starts at and ends at , so it has up steps and down steps. This is invertible: any path from to crosses , and reflecting its segment up to the first crossing recovers a bad path. Thus the number of bad paths equals the number of sequences with up steps among steps, . Finally, , and subtraction gives .
∎Using Stirling’s formula, , so . Remember the shape: exponential growth with base 4 times a polynomial factor . At the end we will see that 4 comes from the location of the singularity of (at ), while comes from its type, a square root.
Exponential generating functions and labelled objects
So far the objects consisted of indistinguishable pieces: two dominoes are alike. Many important objects have labelled pieces: a permutation of , a partition of the set into blocks, or a graph with numbered vertices. For these, ordinary generating-function products count incorrectly and we need another normalization.
Combining two labelled objects (size ) and (size ) into one of size requires distributing the labels : choose which go to , relabelling them in increasing order, and give the rest to . There are ways. Thus the number of combined pairs is
The second expression is an ordinary convolution of the sequences and . This suggests dividing by before packaging.
Three basic exponential generating functions, read as “number of structures of each type on a set of labels”:
| Structure on labels | EGF | |
|---|---|---|
| a set (one way) | ||
| a list (linear order) | ||
| a cycle () |
The missing piece is the set of structures. A set of exactly structures of type is a labelled product of copies, , divided by because the components are unordered. Their labels are disjoint, so the components are always distinct and no symmetries need correcting. Summing over :
This exponential formula explains the name. We will use it three times.
Permutations. Every permutation decomposes uniquely into disjoint cycles (the cycle decomposition), so permutations = sets of cycles, and , the EGF of . The theory checks itself.
Derangements. A derangement is a permutation with no fixed points: a set of cycles of length at least 2. Its EGF is
This is the same formula obtained by inclusion-exclusion, now in one line: are partial sums of the series for , hence . We will see it again as a pole.
Set partitions: Stirling and Bell
A partition of a set is a collection of disjoint nonempty blocks whose union is ; equivalently, it is an equivalence relation on . A block is a “nonempty set,” with EGF .
Both formulas use the exponential formula: sets of exactly blocks, or of any number of blocks. Everything else follows from them.
- Explicit formula. Expanding and extracting gives . This is inclusion-exclusion for surjections from elements to , divided by because the blocks are unnamed.
- Stirling recurrence. : element either joins one of the blocks of a partition of or forms a block by itself.
- Bell recurrence, by differentiating the EGF:
| 1 | 1 | 1 | ||||
| 2 | 1 | 1 | 2 | |||
| 3 | 1 | 3 | 1 | 5 | ||
| 4 | 1 | 7 | 6 | 1 | 15 | |
| 5 | 1 | 15 | 25 | 10 | 1 | 52 |
Integer partitions
Now the opposite case: unlabelled objects. A partition of the integer writes it as a sum of positive integers, disregarding order: . We write the parts in nonincreasing order, .
The product has a direct interpretation: a partition is determined by how many times it uses each part , and the factor chooses that multiplicity ( means “ parts equal to ”). Expanding the product chooses a term from each factor.
Does an infinite product of formal series make sense? Yes, by the same finiteness argument: for the coefficient of only factors with matter, because the rest are . The product of the first factors already has the final coefficient of ; in this sense, coefficient by coefficient in the so-called -adic topology, the infinite product converges. Restricting parts removes factors: for odd parts, ; for distinct parts, each part is used zero or one time and the factor is :
Ferrers diagrams and conjugation
A partition can be drawn as a Ferrers diagram: cells in the first row, in the second, aligned on the left. Reflection across the diagonal exchanges rows and columns and yields another partition of , its conjugate , with = the number of parts of that are . Reflection is an involution, hence a bijection, proving without calculation:
The number of partitions of with at most parts equals the number of partitions of with all parts ,
because the number of rows of is the length of the first row of . The second family has generating function , so the first does too.
The largest square fitting in the corner, the Durfee square, is unchanged by reflection; what remains to its right (the arm) and below it (the leg) are exchanged. Counting by the size of that square gives the identity : a square of cells, an arm that is a partition with at most parts, and a leg that is a partition with parts . By conjugation, the two have the same generating function .
Euler’s theorem and Glaisher’s bijection
The generating-function proof fits on one line, and you will reconstruct it in a guided exercise. Here is J. W. L. Glaisher’s bijective proof (1883). Every integer has a unique representation as with odd.
- Distinct to odd. Replace each part by parts equal to . Repeatedly split each even part in half until none remain.
- Odd to distinct. If the odd part appears times, write in binary, with distinct exponents, and replace those parts by . Equivalently, repeatedly merge pairs of equal parts.
The two operations are inverses because binary representation is unique. For example, maps to , and back: 3 appears times and gives ; 1 appears times and gives .
The pentagonal number theorem
Euler’s product gives an algorithm using operations for : multiplying by is the update , in increasing order of . Euler found a better method by studying the inverse, :
The exponents are the generalized pentagonal numbers The most beautiful proof is another bijection, by F. Franklin (1881), pairing partitions into distinct parts with even and odd numbers of parts except in the pentagonal cases; we do not need it here. Multiplying by and comparing coefficients:
with if . Each uses about preceding terms, so the complete table costs additions.
The symbolic method
For several sections we have been doing the same thing: describing a family of objects using a few operations (union, pairs, sequences, sets) and translating each operation into one on series. Flajolet and Sedgewick turned this practice into a systematic method.
The basic building blocks are the neutral class , one object of size 0 with generating function , and the atomic class , one object of size 1 with generating function . The constructions and their translations are:
| Construction | Unlabelled (OGF) | Labelled (EGF) |
|---|---|---|
| Disjoint union | ||
| Product | (label allocation) | |
| Sequence | ||
| Multiset | (not applicable) | |
| Set | ||
| Cycle | (formula using Euler’s function) |
The SEQ, MSET, SET, and CYC constructions require . In SEQ, MSET, and CYC, a size-0 object would give infinitely many objects of each size, since adding empty objects does not change size, and the series sum would cease to be finite coefficient by coefficient: may still exist in if , but no longer counts anything. In SET the count would remain finite (a factor ), and the case is excluded for uniformity; in the labelled case, with is not even an admissible composition. There are no multisets of labelled objects because two components with disjoint labels are never equal: and coincide.
Proof
Union: the size- objects of are those of plus those of . Unlabelled product: a pair of size consists of an of size and an of size for some ; there are , the coefficient of . Labelled product: the same count multiplied by the label allocations, giving the EGF product. Sequence: is a disjoint union by length, with series ; since , starts at degree , the sum is finite coefficient by coefficient and equals . Multiset: a multiset is determined by each object’s multiplicity; for each of the objects of size a factor selects that multiplicity, and the product is finite in each coefficient by the partition argument. Set: the same, with multiplicities 0 or 1 and factor . Labelled set: by the previous section’s argument, and . Labelled cycle: sequences of components, , grouped by rotation (each cycle of components with disjoint labels corresponds to exactly sequences), give .
∎With the table, counting reduces to specification. Here are familiar examples and new ones:
| Class | Specification | Equation |
|---|---|---|
| Binary trees | ||
| Plane trees (any number of ordered children) | ||
| Integer partitions | ||
| Compositions | ||
| Permutations | ||
| Set partitions | ||
| Involutions (cycles of length 1 or 2) |
The plane-tree equation, , is , that is, : plane trees with nodes also number . Another face of Catalan comes for free from the specification.
A recursive specification such as defines the class as the least fixed point of an operator, just like the inductive definitions in lesson 7. It is solved the same way for series: iterating from fixes at least one more coefficient at each step, because the factor makes the coefficient of degree of depend only on degrees below of . Newton’s method doubles the number of correct coefficients at each step, as the implementation shows.
Asymptotics from singularities
An exact formula does not always exist (there is no closed formula for or ), and when it does, it is not always the useful information: deciding whether exhaustive search is feasible requires knowing how grows. The central idea of analytic combinatorics is that the generating function, viewed as a complex function, already contains that answer in its singularities.
Now convergence matters. If has radius of convergence , it defines an analytic function on the disk whose Taylor coefficients are the . Two principles govern growth.
These two principles make up singularity analysis: the dominant singularity’s location gives the exponential base, and its nature gives the polynomial correction. The first is a classical fact of complex analysis: an analytic function’s Taylor series converges on the largest disk where the function is analytic. For the second, consider the two most common cases.
Poles: rational and meromorphic functions
Proof
By partial fractions, , where is a polynomial plus fractions of the form with . The constant is the limit of as , which by L’Hôpital’s rule equals . The first term contributes exactly , and each remaining fraction contributes . Dividing by gives the stated error.
∎For Fibonacci strips, has roots and , with . With , and
The error decreases exponentially: at it is already of order . Binet’s formula is exactly this with the second pole included.
The same reasoning works if is not rational but is meromorphic, analytic except at poles, on a disk larger than : subtract the singular part of the pole and the remainder is analytic on a larger disk, with exponentially smaller coefficients. Derangements are the perfect example: has a single pole at , with . Moreover, is entire, so the error is smaller than every exponential: , and in fact is the nearest integer to for every .
Square-root singularities
has no poles: it has a branch point at , where the square root stops being analytic. In the complex plane we must cut along to define it. Near that point,
The analytic part, 2 and terms with integer powers of , does not contribute to the first-order asymptotic; dominates. The coefficients of are known exactly from the generalized binomial theorem and Stirling’s formula:
With and the factor : . The base comes from the location; comes from the exponent . The general theorem of Flajolet and Odlyzko (1990), singularity analysis, says that if near its unique dominant singularity , with and analytic in a region slightly larger than the disk (a “delta” surrounding ), then
A simple pole is (factor ); a double pole, (factor ); a square root, (factor , with ). A recursive “tree-like” specification such as or produces, under very general conditions (the Drmota-Lalley-Woods theorem for positive, irreducible, aperiodic systems), a square root at the point where the implicit equation ceases to define as a function of . That is why so many tree families grow like .
The figure shows three lessons worth keeping:
- Only distance from the origin matters. A pole at dominates one at even on the “wrong” half-axis; coefficients alternate in sign and .
- Several singularities at the same distance cause oscillations: with a complex pair , , the ratio has no limit, and what survives is the Cauchy-Hadamard theorem: . In the figure’s example the th root approaches , with occasional drops at when the cosine passes near zero, but in general even it need not have a limit. With nonnegative coefficients, Pringsheim guarantees that one dominant singularity lies on the positive real axis, but others can lie on the same circle: this occurs for , whose coefficients are and whose th root oscillates between 1 and 0.
- Ratio convergence reveals the type. With a simple pole, : geometric convergence. With a square root, : convergence at , the trace of the factor .
Implementation from scratch
We implement series truncated at degree with exact coefficients (Python integers or Fraction), addition, convolution product, inverse by the theorem’s recursion, and composition by Horner’s method. We then use them to check our claims against brute-force enumeration.
from fractions import Fraction
from math import comb, factorial
def _div(x, a0):
"""x / a0 exacto: entero si a0 = ±1, fracción en otro caso."""
return x * a0 if a0 in (1, -1) else Fraction(x) / a0
class Serie:
"""Serie formal de potencias truncada en grado N, con coeficientes exactos."""
def __init__(self, coefs, N):
c = list(coefs)[: N + 1]
self.c = c + [0] * (N + 1 - len(c))
self.N = N
def _lift(self, o):
return o if isinstance(o, Serie) else Serie([o], self.N)
def __add__(self, o):
o = self._lift(o)
return Serie([a + b for a, b in zip(self.c, o.c)], self.N)
__radd__ = __add__
def __neg__(self):
return Serie([-a for a in self.c], self.N)
def __sub__(self, o):
return self + (-self._lift(o))
def __rsub__(self, o):
return self._lift(o) - self
def __mul__(self, o):
o = self._lift(o)
out = [0] * (self.N + 1)
for i, a in enumerate(self.c): # convolución: [x^n] AB = sum_k a_k b_(n-k)
if a:
for j in range(self.N + 1 - i):
out[i + j] += a * o.c[j]
return Serie(out, self.N)
__rmul__ = __mul__
def inversa(self):
a = self.c
if a[0] == 0:
raise ZeroDivisionError("no es invertible: el término independiente es 0")
b = [_div(1, a[0])]
for n in range(1, self.N + 1): # sum_k a_k b_(n-k) = 0 para n >= 1
b.append(_div(-sum(a[k] * b[n - k] for k in range(1, n + 1)), a[0]))
return Serie(b, self.N)
def __truediv__(self, o):
return self * self._lift(o).inversa()
def __rtruediv__(self, o):
return self._lift(o) * self.inversa()
def __pow__(self, k):
r = Serie([1], self.N)
for _ in range(k):
r = r * self
return r
def __call__(self, g):
"""Composición self(g(x)); exige g(0) = 0 para que cada coeficiente sea una suma finita."""
if g.c[0] != 0:
raise ValueError("composición no definida: g(0) debe ser 0")
r = Serie([self.c[self.N]], self.N)
for k in range(self.N - 1, -1, -1): # Horner
r = r * g + self.c[k]
return r
def __getitem__(self, n):
return self.c[n]
def __repr__(self):
t = [f"{a}" + ("" if k == 0 else "x" if k == 1 else f"x^{k}") for k, a in enumerate(self.c) if a][:8]
return " + ".join(t) + " + ..."
N = 15
x = Serie([0, 1], N)
# 1) Tiras con cuadrados (1) y dominós (2): T = 1/(1 - x - x^2), frente a la recursión directa
T = 1 / (1 - x - x**2)
def teselas(n):
return 1 if n <= 1 else teselas(n - 1) + teselas(n - 2) # la última pieza es 1 o 2
print("teselas :", T.c[:12])
print("recursión :", [teselas(n) for n in range(12)])
# 2) Composiciones de n: sucesiones de partes >= 1, A = x/(1-x)
A = x / (1 - x)
print("composiciones:", (1 / (1 - A)).c[:10])
# 3) Recurrencia no homogénea a_n = 2 a_(n-1) + n, a_0 = 0
G = x / ((1 - x) ** 2 * (1 - 2 * x))
a = [0]
for n in range(1, N + 1):
a.append(2 * a[-1] + n)
print("no homogénea:", G.c[:8], " coincide:", G.c == a, " fórmula:", [2 ** (n + 1) - n - 2 for n in range(8)])
# 4) Estrellas y barras: [x^n] 1/(1-x)^3 = C(n+2, 2)
print("estrellas y barras:", (1 / (1 - x) ** 3).c == [comb(n + 2, 2) for n in range(N + 1)])
# 5) Inversa con fracciones y composición con g(0) = 0
print("1/(2 - x) =", 1 / (2 - x))
E = Serie([Fraction(1, factorial(k)) for k in range(N + 1)], N) # e^x
print("n! [x^n] e^(x/(1-x)):", [int(E(A)[n] * factorial(n)) for n in range(8)])Everything agrees: the Fibonacci series with its recursion, compositions with , the nonhomogeneous recurrence with formula , and with stars and bars. The last line composes with ; as an exponential generating function it counts sets of nonempty lists of labels (): .
Now Catalan: solve by fixed-point iteration and Newton’s method, then compare with and three direct enumerations.
N = 14
x = Serie([0, 1], N)
cat = [comb(2 * n, n) // (n + 1) for n in range(N + 1)]
correctos = lambda S: sum(1 for n in range(N + 1) if S[n] == cat[n])
C = Serie([1], N) # punto fijo C <- 1 + x C^2
iter_fijo = []
for _ in range(N):
C = 1 + x * C * C
iter_fijo.append(correctos(C))
print("punto fijo, coeficientes correctos tras cada iteración:", iter_fijo)
C = Serie([1], N) # Newton sobre F(C) = 1 + x C^2 - C
iter_newton = []
for _ in range(4):
C = C + (1 + x * C * C - C) / (1 - 2 * x * C)
iter_newton.append(correctos(C))
print("Newton:", iter_newton)
print("C_n:", C.c)
def dyck(n):
out = []
def rec(s, abiertos, h):
if len(s) == 2 * n:
out.append(s)
return
if abiertos < n:
rec(s + "(", abiertos + 1, h + 1)
if h > 0:
rec(s + ")", abiertos, h - 1)
rec("", 0, 0)
return out
def arboles(n):
"""Árboles binarios con n nodos como tuplas (izq, der); None es el árbol vacío."""
if n == 0:
return [None]
return [(l, r) for k in range(n) for l in arboles(k) for r in arboles(n - 1 - k)]
def parentizaciones(fs):
if len(fs) == 1:
return [fs[0]]
return [f"({a}{b})" for k in range(1, len(fs)) for a in parentizaciones(fs[:k]) for b in parentizaciones(fs[k:])]
print(" n C_n Dyck árboles parentizaciones")
for n in range(1, 9):
print(f"{n:2d} {cat[n]:5d} {len(dyck(n)):5d} {len(arboles(n)):7d} {len(parentizaciones('ABCDEFGHI'[: n + 1])):10d}")
print(parentizaciones("ABCD"))Fixed-point iteration gains exactly one coefficient per step: it starts with two correct coefficients, and , and needs fourteen iterations for all fifteen. Newton reaches 3, 7, and 15: it doubles, as over the reals. This is the same Newton method, applied in the ring of series; computer algebra libraries use it to calculate inverses, roots, and exponentials of series in operations, where is the cost of multiplying two series of degree .
Exponential generating functions need one more operation: for . Differentiating gives , and comparing coefficients gives : a recursion without factorials or infinite series.
from itertools import permutations
def exp_serie(A):
"""exp(A) para A(0) = 0, con la recurrencia de E' = A' E: n e_n = sum_k k a_k e_(n-k)."""
assert A[0] == 0
e = [Fraction(1)]
for n in range(1, A.N + 1):
e.append(sum(k * A[k] * e[n - k] for k in range(1, n + 1)) / n)
return Serie(e, A.N)
def a_conteos(S):
"""De función generatriz exponencial a números: n! [x^n]."""
return [int(S[n] * factorial(n)) for n in range(S.N + 1)]
N = 12
x = Serie([0, 1], N)
ex = exp_serie(x) # e^x
log_inv = Serie([0] + [Fraction(1, k) for k in range(1, N + 1)], N) # log 1/(1-x): ciclos
bell = a_conteos(exp_serie(ex - 1)) # SET(SET_{>=1})
perm = a_conteos(exp_serie(log_inv)) # SET(CYC)
desarr = a_conteos(exp_serie(log_inv - x)) # SET(CYC_{>=2})
print("Bell :", bell)
print("SET(CYC) :", perm[:9])
print("desarreglos:", desarr)
def stirling2(n, k):
return int(((ex - 1) ** k)[n] * factorial(n) / factorial(k))
print("S(5, k) :", [stirling2(5, k) for k in range(6)])
def particiones_conjunto(n):
"""Particiones de {0..n-1} como cadenas de crecimiento restringido: s[i] = bloque de i."""
out = []
def rec(s, m):
if len(s) == n:
out.append(s)
return
for b in range(m + 2):
rec(s + [b], max(m, b))
rec([], -1)
return out
for n in range(1, 9):
ps = particiones_conjunto(n)
por_bloques = [sum(1 for p in ps if max(p) + 1 == k) for k in range(n + 1)]
d = sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))
assert len(ps) == bell[n] and d == desarr[n] and por_bloques == [stirling2(n, k) for k in range(n + 1)]
print("Bell, Stirling y desarreglos coinciden con la enumeración hasta n = 8")
# Repartir {1..n} entre dos cajas con nombre: ordinarias frente a exponenciales
print("ordinarias :", (1 / (1 - x) * (1 / (1 - x))).c[:8])
print("exponenciales:", a_conteos(ex * ex)[:8])The last two lines put the warning from the exponential section in numbers: the product of ordinary functions gives , the exponential product gives , and only the latter counts allocations of labels.
For integer partitions, compare the two algorithms from the section (Euler’s product, , and the pentagonal recurrence, ) with a brute-force generator, and check Euler’s theorem.
import time
def p_euler(n):
"""p(0..n) con el producto de Euler: multiplicar por 1/(1 - x^k) es c_m += c_(m-k)."""
c = [1] + [0] * n
for k in range(1, n + 1):
for m in range(k, n + 1):
c[m] += c[m - k]
return c
def p_pentagonal(n):
"""p(0..n) con la recurrencia del teorema de los números pentagonales."""
p = [1] + [0] * n
for m in range(1, n + 1):
s, j = 0, 1
while True:
g1 = j * (3 * j - 1) // 2
if g1 > m:
break
signo = 1 if j % 2 else -1
s += signo * p[m - g1]
g2 = j * (3 * j + 1) // 2
if g2 <= m:
s += signo * p[m - g2]
j += 1
p[m] = s
return p
def particiones(n, maximo=None):
"""Genera las particiones de n con partes <= maximo, en orden no creciente."""
maximo = n if maximo is None else maximo
if n == 0:
yield ()
return
for k in range(min(n, maximo), 0, -1):
for resto in particiones(n - k, k):
yield (k,) + resto
ref = p_euler(25)
print("p(0..15):", ref[:16])
print("fuerza bruta coincide hasta 25:", all(sum(1 for _ in particiones(n)) == ref[n] for n in range(26)))
print("Euler == pentagonal hasta 500:", p_euler(500) == p_pentagonal(500))
n = 1500
t0 = time.perf_counter(); pe = p_euler(n); t1 = time.perf_counter(); pp = p_pentagonal(n); t2 = time.perf_counter()
print(f"p({n}) tiene {len(str(pe[n]))} cifras; Euler {t1 - t0:.2f} s, pentagonal {t2 - t1:.2f} s")
dist = [sum(1 for l in particiones(m) if len(set(l)) == len(l)) for m in range(26)]
impa = [sum(1 for l in particiones(m) if all(k % 2 for k in l)) for m in range(26)]
print("distintas:", dist[:16])
print("impares :", impa[:16], " iguales hasta 25:", dist == impa)The pentagonal method is already several times faster at , and the difference grows with like . Python integers are exact at any size: has 40 digits and there is nothing to round.
Finally, compare each sequence with the asymptotic predicted by its dominant singularity.
import math
from decimal import Decimal, getcontext
import numpy as np
import matplotlib.pyplot as plt
ns = np.arange(1, 61)
phi = (1 + 5 ** 0.5) / 2
fib = [1, 1]
for _ in range(70):
fib.append(fib[-1] + fib[-2]) # tiras: T_n = F_(n+1)
cat = [comb(2 * n, n) // (n + 1) for n in range(70)]
D = [1, 0]
for n in range(2, 70):
D.append((n - 1) * (D[-1] + D[-2])) # desarreglos
P = p_euler(60)
def rel(exacto, aprox):
return abs(exacto / aprox - 1)
err_fib = [rel(fib[n], phi ** (n + 1) / 5 ** 0.5) for n in ns] # polo simple
err_cat = [rel(cat[n], 4.0 ** n / (math.sqrt(math.pi) * n ** 1.5)) for n in ns] # raíz cuadrada
err_der = [rel(D[n], math.factorial(n) / math.e) for n in ns] # polo, resto entero
err_par = [rel(P[n], math.exp(math.pi * math.sqrt(2 * n / 3)) / (4 * n * math.sqrt(3))) for n in ns]
for n in (10, 30, 60):
print(f"n={n:2d} Fibonacci {err_fib[n-1]:.1e} Catalan {err_cat[n-1]:.1e} "
f"desarreglos {err_der[n-1]:.1e} particiones {err_par[n-1]:.1e}")
print("Catalan, n · error relativo:", [round(float(n * err_cat[n - 1]), 3) for n in (10, 30, 60)], " 9/8 =", 9 / 8)
getcontext().prec = 120 # D_n = entero más próximo a n!/e, con aritmética exacta
e = Decimal(1).exp()
print("D_n == round(n!/e) para 1 <= n <= 60:", all(abs(Decimal(D[n]) - Decimal(math.factorial(n)) / e) < Decimal("0.5") for n in range(1, 61)))
plt.semilogy(ns, err_fib, label="Fibonacci (polo simple)")
plt.semilogy(ns, err_cat, label="Catalan (raíz cuadrada)")
plt.semilogy(ns, err_par, label="particiones (Hardy-Ramanujan)")
plt.semilogy(ns[:17], err_der[:17], label="desarreglos (polo, resto entero)")
plt.xlabel("n"); plt.ylabel("error relativo de la asintótica"); plt.legend(); plt.show()The plot separates three regimes. With a pole and a more distant second pole, error decays geometrically (Fibonacci, a straight line on a logarithmic scale until float64 precision is reached near ). With a pole and an entire remainder, error is superexponential (derangements reach float64 precision near , where their curve is cut off: relative error is of order ). With a square root, error is only : times the Catalan relative error tends to , the next term in the expansion, . Hardy-Ramanujan converges more slowly still, with relative error of order .
The library version
sympy has all of the above built in: series expansions, partial fractions, residues, and combinatorial functions. Use it to check calculations and formulas; for large integer tables, your implementation using Python integers is faster and more transparent.
| Function | What it does |
|---|---|
sp.series(f, x, 0, n) | Taylor expansion through (a truncated formal series) |
sp.apart(f, x) | partial fractions of a rational function |
catalan(n), bell(n), stirling(n, k) | Catalan, Bell, and Stirling numbers (second kind by default) |
partition(n) | exact |
sp.residue(f / x**(n+1), x, 0) | as a residue (Cauchy’s formula) |
import sympy as sp
from sympy.functions.combinatorial.numbers import catalan, bell, partition, stirling
x = sp.symbols("x")
print(sp.series(1 / (1 - x - x**2), x, 0, 10))
print(sp.series((1 - sp.sqrt(1 - 4 * x)) / (2 * x), x, 0, 8))
print(sp.series(sp.exp(sp.exp(x) - 1), x, 0, 6)) # coeficientes = B_n / n!
print(sp.apart(x / ((1 - x)**2 * (1 - 2 * x)), x)) # fracciones simples
print([catalan(n) for n in range(10)])
print([bell(n) for n in range(10)])
print([partition(n) for n in range(15)], partition(200))
print([stirling(6, k) for k in range(7)])
print(sp.residue(1 / (1 - x - x**2) / x**21, x, 0)) # [x^20] como residuo en 0
# Coma flotante: el producto de Euler en float64 deja de ser exacto en cuanto p(n) supera 2^53
def p_float(n):
c = np.zeros(n + 1); c[0] = 1.0
for k in range(1, n + 1):
for m in range(k, n + 1):
c[m] += c[m - k]
return c
pf, pe = p_float(400), p_euler(400)
malos = [n for n in range(401) if int(pf[n]) != pe[n]]
print("primer n con p(n) incorrecto en float64:", malos[0], " p(n) =", pe[malos[0]], " 2^53 =", 2**53)
print("p(400) exacto :", pe[400])
print("p(400) float64:", int(pf[400]))The coefficients of sp.series of are (, , ); apart reproduces the partial fractions from the nonhomogeneous recurrence example, and the residue gives . The last check shows floating-point error: Euler’s product calculated in float64 gives incorrect values from , the first exceeding ; by its final five digits are wrong without warning.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What equation does satisfy?
Step 1 of 4. What is ?
More than one answer may be correct.
partition_count(n) to return as an exact Python int for and beyond, using Euler's product (successively multiplying by ) or the pentagonal recurrence. Do not use floating point or enumerate partitions one by one.def partition_count(n):
"""Número de particiones del entero n >= 0, exacto (int de Python)."""
# tu código: producto de Euler (c[m] += c[m - k]) o recurrencia pentagonal
return 0Summary
- Formal series are sequences with convolution as their product. They need no convergence because each coefficient is a finite sum: is invertible if and only if , and is defined if .
- Ordinary functions for unlabelled objects: union, product, and sequence translate to , , and . Linear recurrences correspond exactly to rational functions, and partial fractions reproduce the characteristic-polynomial method.
- Catalan: gives , counting binary trees, Dyck paths, parentheses, triangulations, and parenthesizations, all linked by the decomposition .
- Exponential functions for labelled objects: the product includes label allocation and sets translate to . This yields (Bell), (Stirling), and (derangements).
- Integer partitions: ; Ferrers conjugation, Euler’s theorem (distinct parts = odd parts), and the pentagonal recurrence, which computes in .
- The symbolic method translates specifications (SEQ, MSET, SET, CYC) into equations automatically.
- Asymptotics: (distance to the nearest singularity) gives the exponential base; a simple pole gives with exponentially small error, while a square root gives with error . Compute coefficients with exact integers and use floating point only for asymptotic comparisons.