Polynomial
Represents a polynomial as ordered Term objects with symbolic coefficients.
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): numberMethodNumerically evaluates the univariate polynomial at a given point
UnsupportedOperationError Thrown for multivariate polynomials.
Parameters
| Name | Type | Description |
|---|---|---|
n | number | JavaScript number at which to evaluate the sole variable. |
Returns
number — A JavaScript-number approximation.
coeffs(variable?: string): CoeffObjectMethodCollects coefficients by power or multidegree.
Parameters
| Name | Type | Description |
|---|---|---|
variable | string | Optional 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(): { … }MethodReturns the positive variable powers shared by every term.
Returns
{ … } — A new variable-to-minimum-power record; variables absent from any term are omitted.
constantTerm(): ExpressionMethodReturns 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): PolynomialConstructorConstructs a polynomial from expression input or deep-copies another polynomial.
PolynomialError Thrown when the parsed expression is not polynomial-like.
UnsupportedOperationError Thrown when input cannot be converted to an expression supported by the polynomial representation.
Parameters
| Name | Type | Description |
|---|---|---|
p | ExpressionInput | Polynomial | Polynomial-like input or an existing polynomial to copy. |
vars | string[] | Variable names in the order used for multidegrees and monomial comparison. When omitted, variables are collected and sorted alphabetically. |
ordering | Ordering | Requested monomial ordering for parsed multivariate input. |
Returns
content(): RationalMethodReturns 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"PropertyRuntime tag used by Nerdamer's polynomial type guard.
defaultOrdering: OrderingPropertyDefault ordering chosen for newly parsed multivariate polynomials.
deg(): numberMethodReturns the degree of the polynomial
Returns
number — The total degree of the leading term under the current ordering.
diff(v?: string, n: number): PolynomialMethodPerforms a derivative with respect to a variable using Term-based operations. Does not rely on the Expression class for differentiation.
Parameters
| Name | Type | Description |
|---|---|---|
v | string | Variable to differentiate; defaults to the first stored variable. |
n | number | Non-negative derivative order. |
Returns
Polynomial — A newly constructed polynomial; order zero returns a deep copy.
div(p: Polynomial): Polynomial[]MethodDivides this polynomial by another polynomial.
Parameters
| Name | Type | Description |
|---|---|---|
p | Polynomial | Divisor polynomial. |
Returns
Polynomial[] — A two-element array containing quotient and remainder as new polynomials.
divides(p: Polynomial): booleanMethodChecks to see if a polynomial divides the given polynomial
Parameters
| Name | Type | Description |
|---|---|---|
p | Polynomial | Polynomial 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): booleanMethodChecks if two polynomials are equal
Parameters
| Name | Type | Description |
|---|---|---|
p | Polynomial | Polynomial to compare. |
Returns
boolean — Whether subtracting `p` produces the zero polynomial.
evaluate(values: { … }): PolynomialMethodEvaluates 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
| Name | Type | Description |
|---|---|---|
values | { … } | Variable names mapped to exact rational-compatible values. |
Returns
Polynomial — A new partially evaluated polynomial; unmentioned variables remain symbolic.
evaluateToRational(values: { … }): RationalMethodNumerically evaluates the polynomial at given values. All variables must be provided values.
UnsupportedOperationError Thrown when any stored variable is missing.
Parameters
| Name | Type | Description |
|---|---|---|
values | { … } | Values for every variable stored by the polynomial. |
Returns
Rational — The exact rational result.
expression: ExpressionPropertyExpression retained from construction or the most recent explicit rebuild.
fromArray(arr: NerdamerInput[], vars: string[]): PolynomialMethodConstructs a polynomial from dense ascending-power coefficients.
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
| Name | Type | Description |
|---|---|---|
arr | NerdamerInput[] | Coefficients ordered from constant term upward. |
vars | string[] | Variable names forming the polynomial base. |
Returns
gcdFree(reduceVariables: boolean, mutate: boolean): PolynomialMethodDivides all terms by their exact numeric content and optionally their common monomial.
Parameters
| Name | Type | Description |
|---|---|---|
reduceVariables | boolean | Also subtract the minimum shared positive power of each variable. |
mutate | boolean | Modify and return this polynomial instead of a deep copy. |
Returns
Polynomial — The normalized target polynomial.
getExpression(): ExpressionMethodReturns the expression retained by the polynomial.
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
Sorts by graded lexicographic order. The abs(power) is first compared and then revlex is used to break ties.
Parameters
Returns
number — A comparator value suitable for `Array.sort`.
grevlexSort(): PolynomialMethodSorts 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.
Sorts by graded lexicographic order. The abs(power) is first compared and then lex is used to break ties.
Parameters
Returns
-1 | 1 — A comparator value suitable for `Array.sort`.
grlexSort(): PolynomialMethodSorts 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(): booleanMethodTests whether the polynomial consists of one constant term.
Returns
boolean — `true` only for the one-term constant representation.
isMultivariate: booleanPropertyWhether the polynomial's variable list contains more than one variable.
isPolynomial(obj: unknown): objMethodChecks if the given object is a Polynomial
Parameters
| Name | Type | Description |
|---|---|---|
obj | unknown | Value to test. |
Returns
obj — Whether `obj` carries Nerdamer's polynomial discriminator.
isZero(): booleanMethodTests whether this polynomial has no terms or a zero leading term.
Returns
boolean — Whether the current term representation is zero.
LC(): ExpressionMethodReturns the leading coefficient under the current ordering.
Returns
Expression — The leading term's internal coefficient reference.
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
Returns
-1 | 1 — A comparator value suitable for `Array.sort`.
lexSort(): PolynomialMethodSorts the terms by lex lexicographic order
Returns
Polynomial — This polynomial after sorting its terms in place.
LM(): TermMethodReturns the leading monomial with unit coefficient.
Returns
Term — A new term with copied powers and variables.
LT(): TermMethodReturns the leading term under the current ordering.
Returns
Term — The internal first term reference.
maxVariableFrequency(): Record<string | number, VariableFrequency>MethodGets 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 } }minus(x: Term | Polynomial): PolynomialMethodSubtracts a Polynomial or a Term
Parameters
| Name | Type | Description |
|---|---|---|
x | Term | Polynomial | Term or polynomial to subtract. |
Returns
Polynomial — A new polynomial. Both operands are left unchanged.
mod(n: ExpressionInput): CoeffObjectMethodReduces each collected coefficient modulo
`n`.
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
| Name | Type | Description |
|---|---|---|
n | ExpressionInput | Modulus passed to the symbolic `mod` operation. |
Returns
CoeffObject — A coefficient object containing the coefficient remainders.
monic(): PolynomialMethodReturns 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[] | undefinedMethodReturns the leading term's multidegree under the current ordering.
Returns
number[] | undefined — The leading term's cached internal multidegree array.
numericCoeffs(): Rational[]MethodGets all the numeric coefficients in the polynomial as Rationals.
Returns
Rational[] — New array containing each term coefficient's internal rational multiplier.
order(ordering?: Ordering): PolynomialMethodReorders the polynomial in the requested ordering if it's not already in that particular ordering.
Parameters
| Name | Type | Description |
|---|---|---|
ordering | Ordering | Requested multivariate ordering. Univariate input is always degree-sorted. |
Returns
Polynomial — This polynomial after sorting its term array in place.
ordering: OrderingPropertyCurrent monomial ordering of terms.
plus(x: Term | Polynomial): PolynomialMethodAdds a Polynomial or a Term.
Parameters
| Name | Type | Description |
|---|---|---|
x | Term | Polynomial | Term or polynomial to add. |
Returns
Polynomial — A new polynomial. Both operands are left unchanged.
polyArraySort(polyArray: Polynomial[], ordering?: Ordering): Polynomial[]MethodSorts an array given a specific ordering using their LT
Parameters
| Name | Type | Description |
|---|---|---|
polyArray | Polynomial[] | Polynomials to reorder. The array itself is sorted in place. |
ordering | Ordering | Monomial ordering used for each polynomial and its leading term. |
Returns
Polynomial[] — The same sorted array after each polynomial has also been reordered.
pow(p: ExpressionInput): PolynomialMethodRaises the polynomial to a power.
PolynomialError Thrown when the powered result is not polynomial-like.
Parameters
| Name | Type | Description |
|---|---|---|
p | ExpressionInput | Exponent accepted by symbolic expression powers. |
Returns
Polynomial — A new polynomial parsed from the powered expression.
Sorts by reverse lexicographic order. The power tuples are subtracted and the first non-negative value from the right is used to sort
Parameters
Returns
number — A comparator value suitable for `Array.sort`.
revlexSort(): PolynomialMethodSorts the terms by revlex reverse lexicographic order
Returns
Polynomial — This polynomial after sorting its terms in place.
sort(): PolynomialMethodSorts the terms in the standard form of decreasing powers.
Returns
stripMonomialGCD(other: Polynomial): { … }MethodNo description is available yet.
Parameters
| Name | Type | Description |
|---|---|---|
other | Polynomial | — |
Returns
{ … }
terms: Term[]PropertyTerms in their current monomial order. The array is mutable.
text(): stringMethodFormats 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): PolynomialMethodMultiplies this polynomial by a term or polynomial.
Parameters
| Name | Type | Description |
|---|---|---|
x | Term | Polynomial | Multiplier. |
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[]MethodConverts univariate coefficients to a dense ascending-power array.
Parameters
| Name | Type | Description |
|---|---|---|
asNumbers | false | Convert each coefficient through JavaScript `Number`. |
variable | string | Optional 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[]MethodConverts dense coefficients to numerator
`bigint`values.
Error Thrown when
`assertInZ`is true and a coefficient is non-integral.
Parameters
| Name | Type | Description |
|---|---|---|
assertInZ | boolean | Reject coefficients whose denominator is not one. |
variable | string | Optional variable to collect as the dense power index. |
Returns
bigint[] — New ascending-power array of coefficient numerators.
toDecimalArray(): Decimal[]MethodConverts dense coefficients to new
`Decimal`values using their expression text.
Returns
Decimal[] — An ascending-power decimal coefficient array.
toExpression(p: PolyType): ExpressionMethodFetches the expression from the given object.
Parameters
| Name | Type | Description |
|---|---|---|
p | PolyType | Polynomial, 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[]): PolynomialMethodConverts 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
Returns
Polynomial — The existing polynomial or a newly constructed one.
toString(): stringMethodReturns the polynomial in a form for easy debugging.
Returns
string — The same canonical term text as Polynomial.text.
variableFrequency(): Record<string, VariableFrequency>MethodCounts 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[]PropertyVariable order used to interpret term multidegrees. The array is mutable.
