Polynomial.js
Polynomial.js is a TypeScript library for parsing and computing univariate polynomials. It supports real, rational, complex, quaternion, modular, and custom coefficient fields.
The library provides immutable arithmetic operations, derivatives, integrals, Euclidean division, greatest common divisors, reciprocal polynomials, and Horner evaluation. It does not calculate roots, but it can construct a polynomial from known roots.
Installation
Polynomial.js requires Node.js 20 or newer when used in Node.js.
Quick Start
import Polynomial from 'polynomial';
Polynomial.setField('R');
const polynomial = Polynomial.fromRoots([1, 2, 3]);
console.log(polynomial.toString()); // x^3-6x^2+11x-6
console.log(polynomial.eval(2)); // 0
console.log(polynomial.derive().toString()); // 3x^2-12x+11
Every polynomial is an instance of the Polynomial class and must be constructed with new. Arithmetic methods return new instances and do not mutate the receiver.
const left = new Polynomial('3x^2');
const sum = left.add('-x^2');
console.log(left.toString()); // 3x^2
console.log(sum.toString()); // 2x^2
CommonJS is supported as well:
const Polynomial = require('polynomial');
Inputs
The constructor and arithmetic methods accept polynomial strings, numbers, coefficient arrays, coefficient maps, and other Polynomial instances.
new Polynomial('23x^4+98x^2+4');
new Polynomial(55);
new Polynomial([1, 2, 3]); // 3x^2+2x+1
new Polynomial({ 3: 4, 5: 9 }); // 9x^5+4x^3
String exponents must be non-negative integers. Whitespace is ignored. Coefficients may contain multiplication and division, while nested polynomial expressions and parentheses are not parsed.
new Polynomial('2 * 3x^2 + 4/5x - 1');
The selected field parses each coefficient, enabling field-specific forms such as fractions, repeating decimals, and complex numbers.
Polynomial.setField('Q');
console.log(new Polynomial('5/3x^3+4/3x').toString());
Polynomial.setField('C');
console.log(new Polynomial('23ix^4+98x^2+i').toString());
Coefficient Fields
The built-in fields are:
| Name |
Coefficients |
Implementation |
R |
Real numbers |
JavaScript numbers |
Q |
Rational numbers |
Fraction.js |
C |
Complex numbers |
Complex.js |
H |
Quaternions |
Quaternion.js |
Zp |
Integers modulo p |
Built in, for example Z7 |
Polynomial.setField() selects the default field for future instances. Each instance captures that field when it is constructed, so changing the default does not alter existing polynomials or their subsequent operations.
Polynomial.setField('Q');
const rational = new Polynomial('1/3x');
Polynomial.setField('R');
console.log(rational.add('1/3x').toString()); // 0.(6)x
Division in Zp requires the divisor to have a multiplicative inverse. Use a prime modulus when all non-zero coefficients must be invertible.
Custom Fields
A custom field can be installed as the default with setField() or passed directly to the constructor. Passing it to the constructor avoids shared configuration and keeps the field local to that polynomial and all results derived from it.
import Polynomial, { type PolynomialField } from 'polynomial';
const field: PolynomialField<number> = {
add: (left, right) => left + Number(right),
sub: (left, right) => left - Number(right),
mul: (left, right) => left * Number(right),
div: (left, right) => left / Number(right),
parse: value => Number(value),
empty: value => value === undefined || value === 0,
pow: (base, exponent) => base ** exponent,
equals: (left, right) => left === Number(right),
characteristic: 0,
magnitude: value => Math.abs(value),
sqrt: value => value < 0 ? null : Math.sqrt(value),
};
const polynomial = new Polynomial('x^2+2x+1', field);
API
Construction and Configuration
new Polynomial(input?, field?) creates a polynomial.
Polynomial.fromRoots(roots, field?) creates a monic polynomial with the given roots.
Polynomial.quotient(modulus, field?) creates the quotient ring defined by a non-constant modulus polynomial.
Polynomial.enumerate(maxDegree, maxElements?) or Polynomial.enumerate(maxDegree, field, maxElements?) enumerates polynomials over a finite prime field.
Polynomial.cyclicCodeGenerators(length, dimension, maxGenerators?) or Polynomial.cyclicCodeGenerators(length, dimension, field, maxGenerators?) finds all generator polynomials for a cyclic code.
Polynomial.setField(field) selects R, Q, C, H, Zp, or a custom field as the default for future instances.
Arithmetic
-
add(value) returns the sum.
-
sub(value) returns the difference.
-
mul(value) returns the product.
-
addmul(left, right) adds the product of two values.
-
div(value) returns the quotient of polynomial long division.
-
mod(value) returns the remainder of polynomial long division.
-
gcd(value) returns the monic greatest common divisor.
-
lcm(value) returns the monic least common multiple.
-
isDivisibleBy(value) reports whether polynomial division has zero remainder.
-
factor() returns the leading unit followed by monic irreducible factors with multiplicity.
-
isIrreducible() reports whether a positive-degree polynomial is irreducible.
-
cyclicCodeBasis(length) returns the shifted basis generated by a divisor of $x^n-1$.
-
compare(value) compares finite-field polynomials in coefficient order.
-
successor() returns the next polynomial in that order.
-
pow(exponent) raises the polynomial to a non-negative integer power.
-
neg() negates every coefficient.
-
reciprocal() reverses the coefficient order relative to the degree.
-
monic() divides every coefficient by the leading coefficient.
-
dispersion(maxShift?) returns the greatest non-negative integer k for which gcd(p(x), p(x+k)) is non-constant.
-
sqrt() returns a polynomial g satisfying g² = p, or null when no polynomial square root exists.
For R, Q, and C, dispersion() derives a finite search bound from the coefficients. A custom field can provide magnitude() and an optional characteristic to enable the same behavior. Otherwise, pass an explicit non-negative maxShift. Non-constant polynomials over a field with positive characteristic have infinite dispersion because shifts by multiples of the characteristic leave the polynomial unchanged.
Polynomial.setField('Q');
const polynomial = new Polynomial('x^3-7x^2+10x'); // roots: 0, 2, 5
console.log(polynomial.dispersion()); // 5
console.log(polynomial.dispersion(4)); // 3
sqrt() uses the root with the principal leading coefficient. Its negation is the second square root. Exact roots are supported over Q and prime fields, while R also permits irrational coefficients and C uses the principal complex coefficient root. Custom fields must provide sqrt(value). Quaternion coefficients are not supported because the coefficient recurrence assumes commutative multiplication.
const square = new Polynomial('9x^4+6x^3-11x^2-4x+4');
const root = square.sqrt();
console.log(root?.toString()); // 3x^2+x-2
console.log(root?.mul(root).toString()); // 9x^4+6x^3-11x^2-4x+4
Calculus and Evaluation
derive(order = 1) returns the requested derivative.
integrate(order = 1) returns the requested antiderivative with zero integration constants.