Represents a polynomial as ordered Term objects with symbolic coefficients.

remarks

Construction accepts polynomial-like expression input, expands bracketed or powered sums when necessary, and collects coefficients using either the supplied variable order or the expression's alphabetically sorted variables. Negative variable powers and other non-polynomial forms are rejected. The object is mutable: ordering methods sort Polynomial.terms in place, and

`gcdFree(..., true)`

edits term coefficients and powers. Arithmetic methods such as Polynomial.plus, Polynomial.minus, and Polynomial.times normally return new polynomials. Public arrays and terms expose mutable internal references; callers that edit them directly must preserve ordering and cached term invariants. Coefficients are stored as

`Expression`

values. Operations such as Polynomial.evaluate convert supplied values to Rational and use exact rational arithmetic; Polynomial.at and numeric array conversions instead use JavaScript numbers and may lose precision. Supported orderings include lexicographic, reverse lexicographic, graded lexicographic, and graded reverse lexicographic order. Univariate polynomials always use descending degree order regardless of the requested multivariate ordering.

Examples

const polynomial = new Polynomial('x^2 + 2*x + 1', ['x']);

polynomial.deg();                    // 2
polynomial.toArray().map(String);    // ["1", "2", "1"]
polynomial.evaluateToRational({ x: 2 }).toString(); // "5"

Members

at(n: number): numberMethod

Numerically evaluates the univariate polynomial at a given point

throws

UnsupportedOperationError Thrown for multivariate polynomials.

Parameters

NameTypeDescription
nnumberJavaScript number at which to evaluate the sole variable.

Returns

number — A JavaScript-number approximation.

coeffs(variable?: string): CoeffObjectMethod

Collects coefficients by power or multidegree.

Parameters

NameTypeDescription
variablestringOptional single main variable. When omitted, keys use all polynomial variables in their stored order.

Returns

CoeffObject — A mutable coefficient object whose expressions are derived from this polynomial.

commonTermVariables(): { … }Method

Returns the positive variable powers shared by every term.

Returns

{ … } — A new variable-to-minimum-power record; variables absent from any term are omitted.

constantTerm(): ExpressionMethod

Returns the coefficient of the trailing constant term.

Returns

Expression — The stored coefficient reference when a constant term is present, otherwise a new zero expression.

Polynomial(p: ExpressionInput | Polynomial, vars?: string[], ordering?: Ordering): PolynomialConstructor

Constructs a polynomial from expression input or deep-copies another polynomial.

throws

PolynomialError Thrown when the parsed expression is not polynomial-like.

throws

UnsupportedOperationError Thrown when input cannot be converted to an expression supported by the polynomial representation.

Parameters

NameTypeDescription
pExpressionInput | PolynomialPolynomial-like input or an existing polynomial to copy.
varsstring[]Variable names in the order used for multidegrees and monomial comparison. When omitted, variables are collected and sorted alphabetically.
orderingOrderingRequested monomial ordering for parsed multivariate input.

Returns

Polynomial

content(): RationalMethod

Returns the content of the polynomial (GCD of all coefficients). Does not rely on the Expression class.

Returns

Rational — A new exact rational greatest common divisor of the numeric coefficients.

dataType: "POL"Property

Runtime tag used by Nerdamer's polynomial type guard.

defaultOrdering: OrderingProperty

Default ordering chosen for newly parsed multivariate polynomials.

deg(): numberMethod

Returns the degree of the polynomial

Returns

number — The total degree of the leading term under the current ordering.

diff(v?: string, n: number): PolynomialMethod

Performs a derivative with respect to a variable using Term-based operations. Does not rely on the Expression class for differentiation.

Parameters

NameTypeDescription
vstringVariable to differentiate; defaults to the first stored variable.
nnumberNon-negative derivative order.

Returns

Polynomial — A newly constructed polynomial; order zero returns a deep copy.

div(p: Polynomial): Polynomial[]Method

Divides this polynomial by another polynomial.

Parameters

NameTypeDescription
pPolynomialDivisor polynomial.

Returns

Polynomial[] — A two-element array containing quotient and remainder as new polynomials.

divides(p: Polynomial): booleanMethod

Checks to see if a polynomial divides the given polynomial

Parameters

NameTypeDescription
pPolynomialPolynomial whose leading term is tested as the dividend.

Returns

boolean — Whether this polynomial's leading term divides `p`'s leading term. This is a monomial divisibility test, not proof that the complete polynomial divides `p`.

eq(p: Polynomial): booleanMethod

Checks if two polynomials are equal

Parameters

NameTypeDescription
pPolynomialPolynomial to compare.

Returns

boolean — Whether subtracting `p` produces the zero polynomial.

evaluate(values: { … }): PolynomialMethod

Evaluates the polynomial at given values using Term-based operations. Supports partial evaluation (substituting some variables while keeping others symbolic). Does not rely on the Expression class for computation.

Parameters

NameTypeDescription
values{ … }Variable names mapped to exact rational-compatible values.

Returns

Polynomial — A new partially evaluated polynomial; unmentioned variables remain symbolic.

evaluateToRational(values: { … }): RationalMethod

Numerically evaluates the polynomial at given values. All variables must be provided values.

throws

UnsupportedOperationError Thrown when any stored variable is missing.

Parameters

NameTypeDescription
values{ … }Values for every variable stored by the polynomial.

Returns

Rational — The exact rational result.

expression: ExpressionProperty

Expression retained from construction or the most recent explicit rebuild.

fromArray(arr: NerdamerInput[], vars: string[]): PolynomialMethod

Constructs a polynomial from dense ascending-power coefficients.

remarks

Entry

`arr[i]`

becomes the coefficient of power

`i`

. When multiple variable names are supplied, their product is treated as one repeated base; this is not a general multidimensional coefficient tensor.

Parameters

NameTypeDescription
arrNerdamerInput[]Coefficients ordered from constant term upward.
varsstring[]Variable names forming the polynomial base.

Returns

Polynomial

gcdFree(reduceVariables: boolean, mutate: boolean): PolynomialMethod

Divides all terms by their exact numeric content and optionally their common monomial.

Parameters

NameTypeDescription
reduceVariablesbooleanAlso subtract the minimum shared positive power of each variable.
mutatebooleanModify and return this polynomial instead of a deep copy.

Returns

Polynomial — The normalized target polynomial.

getExpression(): ExpressionMethod

Returns the expression retained by the polynomial.

remarks

This is an internal reference, not a copy. The term array is the operative representation for many methods, and direct term mutation is not guaranteed to rebuild this stored expression automatically.

Returns

Expression

grevlex(a: Term, b: Term): numberMethod

Sorts by graded lexicographic order. The abs(power) is first compared and then revlex is used to break ties.

Parameters

NameTypeDescription
aTermFirst term to compare.
bTermSecond term to compare.

Returns

number — A comparator value suitable for `Array.sort`.

grevlexSort(): PolynomialMethod

Sorts the terms by graded lexicographic order grevlex first compares their powers. If their powers are equal then it breaks ties using revlex reverse lexicographic order.

Returns

Polynomial — This polynomial after sorting its terms in place.

grlex(a: Term, b: Term): -1 | 1Method

Sorts by graded lexicographic order. The abs(power) is first compared and then lex is used to break ties.

Parameters

NameTypeDescription
aTermFirst term to compare.
bTermSecond term to compare.

Returns

-1 | 1 — A comparator value suitable for `Array.sort`.

grlexSort(): PolynomialMethod

Sorts the terms by graded lexicographic order grlex first compares their powers. If their powers are equal then it breaks ties using lex lexicographic order.

Returns

Polynomial — This polynomial after sorting its terms in place.

isConstant(): booleanMethod

Tests whether the polynomial consists of one constant term.

Returns

boolean — `true` only for the one-term constant representation.

isMultivariate: booleanProperty

Whether the polynomial's variable list contains more than one variable.

isPolynomial(obj: unknown): objMethod

Checks if the given object is a Polynomial

Parameters

NameTypeDescription
objunknownValue to test.

Returns

obj — Whether `obj` carries Nerdamer's polynomial discriminator.

isZero(): booleanMethod

Tests whether this polynomial has no terms or a zero leading term.

Returns

boolean — Whether the current term representation is zero.

LC(): ExpressionMethod

Returns the leading coefficient under the current ordering.

Returns

Expression — The leading term's internal coefficient reference.

lex(a: Term, b: Term): -1 | 1Method

Sorts by lexicographic order. The power tuples are subtracted and the first non-negative value from the left is used to sort. Note that variables are first sorted in alphabetical order.

Parameters

NameTypeDescription
aTermFirst term to compare.
bTermSecond term to compare.

Returns

-1 | 1 — A comparator value suitable for `Array.sort`.

lexSort(): PolynomialMethod

Sorts the terms by lex lexicographic order

Returns

Polynomial — This polynomial after sorting its terms in place.

LM(): TermMethod

Returns the leading monomial with unit coefficient.

Returns

Term — A new term with copied powers and variables.

LT(): TermMethod

Returns the leading term under the current ordering.

Returns

Term — The internal first term reference.

maxVariableFrequency(): Record<string | number, VariableFrequency>Method

Gets the maximum variable occurrence in the polynomial. If two or more variables have an equal number of occurrences then they will be included in the set

Returns

Record<string | number, VariableFrequency> — A new record containing every variable tied for the greatest term-occurrence count.

Examples

new Polynomial('q^3*a+2*q^2*a').maxVariableFrequency();
// { a: { variable: 'a', count: 2, deg: 2 },
//   q: { variable: 'q', count: 2, deg: 5 } }

Reduces each collected coefficient modulo

`n`

.

remarks

The polynomial itself is not modified. The returned coefficient object is derived from the current polynomial and stores the reduced coefficient expressions at the same power keys.

Parameters

NameTypeDescription
nExpressionInputModulus passed to the symbolic `mod` operation.

Returns

CoeffObject — A coefficient object containing the coefficient remainders.

monic(): PolynomialMethod

Returns a copy with the leading nonconstant coefficient normalized to one. Constant polynomials are copied without coefficient normalization.

Returns

Polynomial — A new polynomial with a unit leading coefficient when normalization applies.

multideg(): number[] | undefinedMethod

Returns the leading term's multidegree under the current ordering.

Returns

number[] | undefined — The leading term's cached internal multidegree array.

numericCoeffs(): Rational[]Method

Gets all the numeric coefficients in the polynomial as Rationals.

Returns

Rational[] — New array containing each term coefficient's internal rational multiplier.

order(ordering?: Ordering): PolynomialMethod

Reorders the polynomial in the requested ordering if it's not already in that particular ordering.

Parameters

NameTypeDescription
orderingOrderingRequested multivariate ordering. Univariate input is always degree-sorted.

Returns

Polynomial — This polynomial after sorting its term array in place.

ordering: OrderingProperty

Current monomial ordering of terms.

polyArraySort(polyArray: Polynomial[], ordering?: Ordering): Polynomial[]Method

Sorts an array given a specific ordering using their LT

Parameters

NameTypeDescription
polyArrayPolynomial[]Polynomials to reorder. The array itself is sorted in place.
orderingOrderingMonomial ordering used for each polynomial and its leading term.

Returns

Polynomial[] — The same sorted array after each polynomial has also been reordered.

Raises the polynomial to a power.

throws

PolynomialError Thrown when the powered result is not polynomial-like.

Parameters

NameTypeDescription
pExpressionInputExponent accepted by symbolic expression powers.

Returns

Polynomial — A new polynomial parsed from the powered expression.

revlex(a: Term, b: Term): numberMethod

Sorts by reverse lexicographic order. The power tuples are subtracted and the first non-negative value from the right is used to sort

Parameters

NameTypeDescription
aTermFirst term to compare.
bTermSecond term to compare.

Returns

number — A comparator value suitable for `Array.sort`.

revlexSort(): PolynomialMethod

Sorts the terms by revlex reverse lexicographic order

Returns

Polynomial — This polynomial after sorting its terms in place.

stripMonomialGCD(other: Polynomial): { … }Method

No description is available yet.

Parameters

NameTypeDescription
otherPolynomial

Returns

{ … }

terms: Term[]Property

Terms in their current monomial order. The array is mutable.

text(): stringMethod

Formats the current ordered terms as canonical parser text.

Returns

string — `"0"` for an empty/zero term representation, otherwise the joined term text.

times(x: Term | Polynomial): PolynomialMethod

Multiplies this polynomial by a term or polynomial.

Parameters

NameTypeDescription
xTerm | PolynomialMultiplier.

Returns

Polynomial — A new polynomial. Term multiplication copies this polynomial before updating its terms; polynomial multiplication rebuilds from symbolic expressions.

toArray(asNumbers: false, variable?: string): Expression[]Method

Converts univariate coefficients to a dense ascending-power array.

Parameters

NameTypeDescription
asNumbersfalseConvert each coefficient through JavaScript `Number`.
variablestringOptional variable to collect as the dense power index.

Returns

Expression[] — New coefficient array with missing powers filled by zero expressions.

toBigIntArray(assertInZ: boolean, variable?: string): bigint[]Method

Converts dense coefficients to numerator

`bigint`

values.

throws

Error Thrown when

`assertInZ`

is true and a coefficient is non-integral.

Parameters

NameTypeDescription
assertInZbooleanReject coefficients whose denominator is not one.
variablestringOptional variable to collect as the dense power index.

Returns

bigint[] — New ascending-power array of coefficient numerators.

toDecimalArray(): Decimal[]Method

Converts dense coefficients to new

`Decimal`

values using their expression text.

Returns

Decimal[] — An ascending-power decimal coefficient array.

toExpression(p: PolyType): ExpressionMethod

Fetches the expression from the given object.

Parameters

NameTypeDescription
pPolyTypePolynomial, expression, or parser text to convert.

Returns

Expression — The polynomial's stored expression reference, or the parsed expression for non-polynomial input.

toPolynomial(p: PolyType, ordering?: Ordering, variables?: string[]): PolynomialMethod

Converts a string to a Polynomial. If a polynomial is provided, it's returned untouched. If a polynomial is provided and no ordering, then the polynomial's ordering will be used. If no ordering is provided for all others then the Polynomial.defaultOrdering will be used.

Parameters

NameTypeDescription
pPolyTypeValue to convert.
orderingOrderingOrdering to apply. Passing an existing polynomial may reorder it in place.
variablesstring[]Variable order used only when constructing a new polynomial.

Returns

Polynomial — The existing polynomial or a newly constructed one.

toString(): stringMethod

Returns the polynomial in a form for easy debugging.

Returns

string — The same canonical term text as Polynomial.text.

variableFrequency(): Record<string, VariableFrequency>Method

Counts each variable's term occurrences and accumulated degree.

Returns

Record<string, VariableFrequency> — A new record keyed by variable. Each entry reports its name, number of nonzero-power terms, and sum of powers across those terms.

variables: string[]Property

Variable order used to interpret term multidegrees. The array is mutable.