Generating functions
A generating function packs a whole sequence into one object, , and turns questions about sequences into algebra. Here a series is computed lazily: you ask for as many coefficients as you need, and each one is an exact fraction.
Series as objects
import { series, knownSeries, egf } from "@ratmath/discrete";
series([1, 1]).pow(5).toString(7); // "1 + 5x + 10x^2 + 10x^3 + 5x^4 + x^5 + O(x^7)"
series([1, -1]).reciprocal().toString(5); // "1 + x + x^2 + x^3 + x^4 + O(x^5)"
series([1, 1]).log().toString(5); // "x − (1/2)x^2 + (1/3)x^3 − (1/4)x^4 + O(x^5)"
knownSeries.binomial("1/2").toString(5); // "1 + (1/2)x − (1/8)x^2 + (1/16)x^3 − (5/128)x^4 + O(x^5)"
A series is given by a coefficient list, a constant, or a rule . Every operation returns another lazy series: sums, products, when , when , derivative and integral, and , , and for rational . Coefficients are remembered once computed, so asking for 200 terms after 100 does only the new work.
The rules behind the operations are the usual recurrences for coefficients. For the reciprocal , comparing coefficients of gives
and for , differentiating gives , so . Both are exact over the rationals.
Counting with products
Multiplying ordinary generating functions convolves sequences, which is how choices combine. Euler's product for partitions, , counts the ways to write as a sum of positive parts; knownSeries.partitions() computes it by his pentagonal-number recurrence. The Catalan series solves .
knownSeries.partitions().terms(15).join(" "); // "1 1 2 3 5 7 11 15 22 30 42 56 77 101 135"
knownSeries.catalan().toString(8); // "1 + x + 2x^2 + 5x^3 + 14x^4 + 42x^5 + 132x^6 + 429x^7 + O(x^8)"
Exponential generating functions
For labelled objects the right tool is . Products then count ways to split a label set and build one structure on each part. A set partition is a set of non-empty blocks, so the Bell numbers have the EGF :
series([0, 1]).exp().subtract(1).exp().terms(10, { egf: true }).join(" ");
// "1 1 2 5 15 52 203 877 4140 21147": the Bell numbers
egf(() => 1).multiply(egf(() => 1)).terms(6, { egf: true }); // 1, 2, 4, 8, 16, 32: e^x·e^x = e^{2x}
terms(n, { egf: true }) multiplies the th coefficient by , so it reads off the counts.
Rational generating functions
A quotient of polynomials with is the generating function of a sequence satisfying a linear recurrence, read off from . rationalSeries keeps the two polynomials, so the recurrence comes back exactly:
import { rationalSeries } from "@ratmath/discrete";
const j = rationalSeries([1], [1, -1, -2]); // 1/(1 − x − 2x²)
j.terms(8).join(" "); // "1 1 3 5 11 21 43 85"
String(j.recurrence()); // "a(n) = a(n−1) + 2·a(n−2), from a(0) = 1, a(1) = 1"
Going the other way, every linear recurrence has generatingFunction(); see Recurrences.
@ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.