Polynomials

Polynomial toolkit

The tools the rest of the library is built from, exposed for direct use: exact polynomial arithmetic over Q, resultants and discriminants, root counting, interpolation and partial fractions. In the expression language, x is the variable: (x + 1)^3 is a polynomial.

Resultants

The resultant Res(p, q) is a single number, built from the coefficients alone (the determinant of the Sylvester matrix), that is 0 exactly when p and q have a common root. Over the roots,

Res(p, q) = lc(p)^deg q · lc(q)^deg p · Π (αᵢ − βⱼ)

which is why resultants manufacture polynomials for sums and products of algebraic numbers: put a parameter t inside q and the resultant becomes a polynomial in t that vanishes at every αᵢ + βⱼ.

Discriminants

The discriminant of p (degree n, leading coefficient a) is (−1)^(n(n−1)/2)·Res(p, p′)/a = a^(2n−2)·Π_(i

Counting real roots

A Sturm sequence counts distinct real roots in any interval (a, b] exactly, without finding them: count sign changes of p, p′, −rem(p, p′), … at a and at b, and subtract. countroots(p, a, b) works on the square-free factors, so repeated roots count once.

Interpolation

Through n points with distinct x there is exactly one polynomial of degree below n. Newton's divided differences build it with exact rationals: interpolate([[0, 1], [1, 3], [2, 7]]) gives x² + x + 1.

Partial fractions

A fraction num/den splits into a polynomial plus a sum of simple pieces, one group for each irreducible factor f of den with multiplicity e:

num/den = q(x) + Σ_f Σ_(k ≤ e) aₖ(x)/f(x)ᵏ, deg aₖ < deg f

The library factors den over the integers, splits the fraction between coprime factors with the extended Euclidean algorithm (s·U + t·V = 1 gives N/(UV) = Nt/U + Ns/V), and then expands each A/fᵉ in powers of f by repeated division. This is the step behind integrating rational functions.

In code

import { polys, resultant, discriminant, countRoots, interpolate, partialFractions } from "@ratmath/algebraic";
resultant([-2, 0, 1], [-3, 0, 1]).toString();  // "1"
discriminant([-1, -1, 0, 1]).toString();       // "-23"
countRoots([1, -5, 0, 0, 0, 1], 0, 2);          // 2
interpolate([[0, 1], [1, 3], [2, 7]]).map(String);  // ["1", "1", "1"]
partialFractions([1], [0, -1, 0, 1]);
// { polynomial: [], terms: [{ factor: [-1n, 1n], power: 1, numerator: [1/2] }, …] }
polys.gcdExt([-1, 0, 1], [1, 1]);   // { gcd, s, t } with s·p + t·q = gcd
polys.format(polys.compose([0, 0, 1], [1, 1]));  // "x² + 2x + 1"

Inputs: coefficient arrays, constant first, of numbers, BigInts, strings like "3/4" or Core Rationals. Outputs are arrays of Core Rationals.

Try itEdit the code and run it with @ratmath/algebraic and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs