Polynomial

Symbolica documentation for getting started, symbolic expressions, numerical evaluation, pattern matching, and APIs in Python and Rust.

Polynomial

Polynomial()

A Symbolica polynomial with rational coefficients.

Methods

Name Description
__add__ Add two polynomials self and rhs, returning the result.
__contains__ Check if the polynomial contains the given variable.
__copy__ Copy the polynomial.
__eq__ Check if two polynomials are equal.
__floordiv__ Divide the polynomial self by rhs, rounding down, returning the result.
__ge__ Check if the polynomial is greater than or equal to an integer.
__gt__ Check if the polynomial is greater than an integer.
__le__ Check if the polynomial is less than or equal to an integer.
__lt__ Check if the polynomial is less than an integer.
__mod__ Compute the remainder of the division of self by rhs.
__mul__ Multiply two polynomials self and rhs, returning the result.
__ne__ Check if two polynomials are not equal.
__neg__ Negate the polynomial.
__pow__ Raise the polynomial to the power of exp, returning the result.
__radd__ Add two polynomials self and rhs, returning the result.
__rmul__ Multiply two polynomials self and rhs, returning the result.
__rsub__ Subtract polynomials self from rhs, returning the result.
__str__ Print the polynomial in a human-readable format.
__sub__ Subtract polynomials rhs from self, returning the result.
__truediv__ Divide the polynomial self by rhs if possible, returning the result.
adjoin Adjoin the coefficient ring of this polynomial R[a] with b, whose minimal polynomial is R[a][b] and form R[b]
approximate_roots Approximate all complex roots of a univariate polynomial, given a maximal number of iterations and a given tolerance
coefficient_list Get the coefficient list, optionally in the variables xs.
contains Check if the polynomial contains the given variable.
content Get the content, i.e., the GCD of the coefficients.
degree Get the degree of the polynomial in var.
derivative Take a derivative in x.
evaluate Evaluate the polynomial at point input.
evaluate_complex Evaluate the polynomial at point input with complex input.
extended_gcd Compute the extended GCD of two polynomials, yielding the GCD and the Bezout coefficients s and t such that self * s + rhs * t = gcd(self, rhs).
factor Factorize the polynomial.
factor_square_free Compute the square-free factorization of the polynomial.
format Convert the polynomial into a human-readable string, with tunable settings.
gcd Compute the greatest common divisor (GCD) of two or more polynomials.
get_variables Get the list of variables in the internal ordering of the polynomial.
groebner_basis Compute the Groebner basis of a polynomial system
integrate Integrate the polynomial in x.
interpolate Perform Newton interpolation in the variable x given the sample points sample_points and the values values.
isolate_roots Isolate the real roots of the polynomial
lcoeff Get the leading coefficient.
monic Get the monic part of the polynomial, i.e., the polynomial divided by its leading coefficient.
nterms Get the number of terms in the polynomial.
parse Parse a polynomial with integer coefficients from a string
primitive Get the primitive part of the polynomial, i.e., the polynomial with the content removed.
quot_rem Divide self by rhs, returning the quotient and remainder.
reduce Completely reduce the polynomial w.r.t the polynomials gs
reorder Reorder the polynomial in-place to use the given variable order.
replace Replace the variable x with a polynomial v.
resultant Compute the resultant of two polynomials with respect to the variable var.
simplify_algebraic_number Find the minimal polynomial for the algebraic number represented by this polynomial expressed in the number field defined by minimal_poly.
to_expression Convert the polynomial to an expression.
to_finite_field Convert the coefficients of the polynomial to a finite field with prime prime.
to_latex Convert the polynomial into a LaTeX string.
to_number_field Convert the coefficients of the polynomial to a number field defined by the minimal polynomial min_poly.

__add__

Polynomial.__add__(rhs: Polynomial | int) -> Polynomial

Add two polynomials self and rhs, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__contains__

Polynomial.__contains__(var: Expression) -> bool

Check if the polynomial contains the given variable.

Parameters

  • var (Expression) The variable whose presence should be tested.

__copy__

Polynomial.__copy__() -> Polynomial

Copy the polynomial.

__eq__

Polynomial.__eq__(rhs: Polynomial | int) -> bool

Check if two polynomials are equal.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__floordiv__

Polynomial.__floordiv__(rhs: Polynomial) -> Polynomial

Divide the polynomial self by rhs, rounding down, returning the result.

Parameters

  • rhs (Polynomial) The right-hand-side operand.

__ge__

Polynomial.__ge__(rhs: int) -> bool

Check if the polynomial is greater than or equal to an integer.

Parameters

  • rhs (int) The right-hand-side operand.

__gt__

Polynomial.__gt__(rhs: int) -> bool

Check if the polynomial is greater than an integer.

Parameters

  • rhs (int) The right-hand-side operand.

__le__

Polynomial.__le__(rhs: int) -> bool

Check if the polynomial is less than or equal to an integer.

Parameters

  • rhs (int) The right-hand-side operand.

__lt__

Polynomial.__lt__(rhs: int) -> bool

Check if the polynomial is less than an integer.

Parameters

  • rhs (int) The right-hand-side operand.

__mod__

Polynomial.__mod__(rhs: Polynomial) -> Polynomial

Compute the remainder of the division of self by rhs.

Parameters

  • rhs (Polynomial) The right-hand-side operand.

__mul__

Polynomial.__mul__(rhs: Polynomial | int) -> Polynomial

Multiply two polynomials self and rhs, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__ne__

Polynomial.__ne__(rhs: Polynomial | int) -> bool

Check if two polynomials are not equal.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__neg__

Polynomial.__neg__() -> Polynomial

Negate the polynomial.

__pow__

Polynomial.__pow__(exp: int) -> Polynomial

Raise the polynomial to the power of exp, returning the result.

Parameters

  • exp (int) The exponent.

__radd__

Polynomial.__radd__(rhs: Polynomial | int) -> Polynomial

Add two polynomials self and rhs, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__rmul__

Polynomial.__rmul__(rhs: Polynomial | int) -> Polynomial

Multiply two polynomials self and rhs, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__rsub__

Polynomial.__rsub__(rhs: Polynomial | int) -> Polynomial

Subtract polynomials self from rhs, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__str__

Polynomial.__str__() -> str

Print the polynomial in a human-readable format.

__sub__

Polynomial.__sub__(rhs: Polynomial | int) -> Polynomial

Subtract polynomials rhs from self, returning the result.

Parameters

  • rhs (Polynomial | int) The right-hand-side operand.

__truediv__

Polynomial.__truediv__(rhs: Polynomial) -> Polynomial

Divide the polynomial self by rhs if possible, returning the result.

Parameters

  • rhs (Polynomial) The right-hand-side operand.

adjoin

Polynomial.adjoin(
    min_poly: Polynomial,
    new_symbol: Expression | None = None,
) -> tuple[Polynomial, Polynomial, Polynomial]

Adjoin the coefficient ring of this polynomial R[a] with b, whose minimal polynomial is R[a][b] and form R[b]. Also return the new representation of a and b.

b must be irreducible over R and R[a]; this is not checked.

If new_symbol is provided, the variable of the new extension will be renamed to it. Otherwise, the variable of the new extension will be the same as that of b.

Examples

from symbolica import *
sqrt2 = P('a^2-2')
sqrt23 = P('b^2-a-3')
(min_poly, rep2, rep23) = sqrt2.adjoin(sqrt23)

# convert to number field
a = P('a^2+b').replace(S('b'), rep23).replace(S('a'), rep2).to_number_field(min_poly)

Parameters

  • min_poly (Polynomial) The minimal polynomial that defines the algebraic extension.
  • new_symbol (Expression | None) The symbol chosen for the adjoined generator.

approximate_roots

Polynomial.approximate_roots(max_iterations: int, tolerance: float) -> list[tuple[complex, int]]

Approximate all complex roots of a univariate polynomial, given a maximal number of iterations and a given tolerance. Returns the roots and their multiplicity.

Examples

p = E('x^10+9x^7+4x^3+2x+1').to_polynomial()
for (r, m) in p.approximate_roots(1000, 1e-10):
    print(r, m)

Parameters

  • max_iterations (int) The maximum number of iterations for the root finder.
  • tolerance (float) The convergence tolerance for the root finder.

coefficient_list

Polynomial.coefficient_list(xs: Expression | Sequence[Expression] | None = None) -> list[tuple[list[int], Polynomial]]

Get the coefficient list, optionally in the variables xs.

Examples

from symbolica import *
x = S('x')
p = E('x*y+2*x+x^2').to_polynomial()
for n, pp in p.coefficient_list(x):
    print(n, pp)

Parameters

  • xs (Expression | Sequence[Expression] | None) The variables with respect to which coefficients should be listed.

contains

Polynomial.contains(var: Expression) -> bool

Check if the polynomial contains the given variable.

Parameters

  • var (Expression) The variable whose presence should be tested.

content

Polynomial.content() -> Polynomial

Get the content, i.e., the GCD of the coefficients.

Examples

from symbolica import *
p = E('3x^2+6x+9').to_polynomial()
print(p.content())

degree

Polynomial.degree(var: Expression) -> int

Get the degree of the polynomial in var.

Parameters

  • var (Expression) The variable whose degree should be returned.

derivative

Polynomial.derivative(x: Expression) -> Polynomial

Take a derivative in x.

Examples

from symbolica import *
x = S('x')
p = E('x^2+2').to_polynomial()
print(p.derivative(x))

Parameters

  • x (Expression) The variable with respect to which to differentiate.

evaluate

Polynomial.evaluate(input: npt.ArrayLike) -> float

Evaluate the polynomial at point input.

Examples

from symbolica import *
P('x*y+2*x+x^2').evaluate([2., 3.])

Yields 14.0.

Parameters

  • input (npt.ArrayLike) The input value.

evaluate_complex

Polynomial.evaluate_complex(input: npt.ArrayLike) -> complex

Evaluate the polynomial at point input with complex input.

Examples

from symbolica import *
P('x*y+2*x+x^2').evaluate([2+1j, 3+2j])

Yields 11+13j.

Parameters

  • input (npt.ArrayLike) The input value.

extended_gcd

Polynomial.extended_gcd(rhs: Polynomial) -> tuple[Polynomial, Polynomial, Polynomial]

Compute the extended GCD of two polynomials, yielding the GCD and the Bezout coefficients s and t such that self * s + rhs * t = gcd(self, rhs).

Examples

from symbolica import *
E('(1+x)(20+x)').to_polynomial().extended_gcd(E('x^2+2').to_polynomial())

yields (1, 1/67-7/402*x, 47/134+7/402*x).

Parameters

  • rhs (Polynomial) The right-hand-side operand.

factor

Polynomial.factor() -> list[tuple[Polynomial, int]]

Factorize the polynomial.

Examples

from symbolica import *
p = E('(x+1)(x+2)(x+3)(x+4)(x+5)(x^2+6)(x^3+7)(x+8)(x^4+9)(x^5+x+10)').expand().to_polynomial()
print('Factorization of {}:'.format(p))
for f, exp in p.factor():
    print(' ({})^{}'.format(f, exp))

factor_square_free

Polynomial.factor_square_free() -> list[tuple[Polynomial, int]]

Compute the square-free factorization of the polynomial.

Examples

from symbolica import *
p = E('3*(2*x^2+y)(x^3+y)^2(1+4*y)^2(1+x)').expand().to_polynomial()
print('Square-free factorization of {}:'.format(p))
for f, exp in p.factor_square_free():
    print(' ({})^{}'.format(f, exp))

format

Polynomial.format(
    mode: PrintMode = PrintMode.Symbolica,
    max_line_length: int | None = 80,
    indentation: int = 4,
    fill_indented_lines: bool = True,
    terms_on_new_line: bool = False,
    color_top_level_sum: bool = True,
    color_builtin_symbols: bool = True,
    bracket_level_colors: Sequence[int] | None = [244, 25, 97, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60],
    print_ring: bool = True,
    symmetric_representation_for_finite_field: bool = False,
    explicit_rational_polynomial: bool = False,
    number_thousands_separator: str | None = None,
    multiplication_operator: str = '*',
    double_star_for_exponentiation: bool = False,
    square_brackets_for_function: bool = False,
    function_brackets: tuple[str, str] = ('(', ')'),
    num_exp_as_superscript: bool = True,
    precision: int | None = None,
    show_namespaces: bool = False,
    hide_namespace: str | None = None,
    include_attributes: bool = False,
    max_terms: int | None = None,
    custom_print_mode: int | None = None,
) -> str

Convert the polynomial into a human-readable string, with tunable settings.

Examples

p = FiniteFieldPolynomial.parse("3*x^2+2*x+7*x^3", ['x'], 11)
print(p.format(symmetric_representation_for_finite_field=True))

Yields z³⁴+x^(x+2)+y⁴+f(x,x²)+128_378_127_123 z^(2/3) w² x⁻¹ y⁻¹+3/5.

Parameters

  • mode (PrintMode) The mode that controls how the input is interpreted or formatted.
  • max_line_length (int | None) The preferred maximum line length before wrapping.
  • indentation (int) The number of spaces used for wrapped lines.
  • fill_indented_lines (bool) Whether wrapped lines should be padded to the configured indentation.
  • terms_on_new_line (bool) Whether wrapped output should place terms on separate lines.
  • color_top_level_sum (bool) Whether top-level sums should be colorized.
  • color_builtin_symbols (bool) Whether built-in symbols should be colorized.
  • bracket_level_colors (Sequence[int] | None) The colors assigned to successive nested bracket levels.
  • print_ring (bool) Whether the coefficient ring should be included in the printed output.
  • symmetric_representation_for_finite_field (bool) Whether finite-field elements should be printed using symmetric representatives.
  • explicit_rational_polynomial (bool) Whether rational polynomials should be printed explicitly as numerator and denominator.
  • number_thousands_separator (str | None) The separator inserted between groups of digits in printed integers.
  • multiplication_operator (str) The string used to print multiplication.
  • double_star_for_exponentiation (bool) Whether exponentiation should be printed as ** instead of ^.
  • square_brackets_for_function (bool) Whether function calls should be printed with square brackets.
  • function_brackets (tuple[str, str]) The opening and closing brackets used when printing function arguments.
  • num_exp_as_superscript (bool) Whether small integer exponents should be printed as superscripts.
  • precision (int | None) The decimal precision used when printing numeric coefficients.
  • show_namespaces (bool) Whether namespaces should be included in the formatted output.
  • hide_namespace (str | None) A namespace prefix to omit from printed symbol names.
  • include_attributes (bool) Whether symbol attributes should be included in the printed output.
  • max_terms (int | None) The maximum number of terms to print before truncating the output.
  • custom_print_mode (int | None) A custom print-mode identifier passed through to custom print callbacks.

gcd

Polynomial.gcd(*rhs: Polynomial) -> Polynomial

Compute the greatest common divisor (GCD) of two or more polynomials.

Parameters

  • rhs (Polynomial) The right-hand-side operand.

get_variables

Polynomial.get_variables() -> Sequence[Expression]

Get the list of variables in the internal ordering of the polynomial.

groebner_basis

Polynomial.groebner_basis(
    system: Sequence[Polynomial],
    grevlex: bool = True,
    print_stats: bool = False,
) -> list[Polynomial]

Compute the Groebner basis of a polynomial system.

If grevlex=True, reverse graded lexicographical ordering is used, otherwise the ordering is lexicographical.

If print_stats=True intermediate statistics will be printed.

Examples

basis = Polynomial.groebner_basis(
    [E("a b c d - 1").to_polynomial(),
    E("a b c + a b d + a c d + b c d").to_polynomial(),
    E("a b + b c + a d + c d").to_polynomial(),
    E("a + b + c + d").to_polynomial()],
    grevlex=True,
    print_stats=True
)
for p in basis:
    print(p)

Parameters

  • system (Sequence[Polynomial]) The equations or polynomials that define the system.
  • grevlex (bool) Whether graded reverse lexicographic ordering should be used.
  • print_stats (bool) Whether Groebner basis statistics should be printed during computation.

integrate

Polynomial.integrate(x: Expression) -> Polynomial

Integrate the polynomial in x.

Examples

from symbolica import *
x = S('x')
p = E('x^2+2').to_polynomial()
print(p.integrate(x))

Parameters

  • x (Expression) The variable with respect to which to integrate.

interpolate

Polynomial.interpolate(
    x: Expression,
    sample_points: Sequence[Expression | int],
    values: Sequence[Polynomial],
) -> Polynomial

Perform Newton interpolation in the variable x given the sample points sample_points and the values values.

Examples

x, y = S('x', 'y')
a = Polynomial.interpolate(
        x, [4, 5], [(y**2+5).to_polynomial(), (y**3).to_polynomial()])
print(a)  # 25-5*x+5*y^2-y^2*x-4*y^3+y^3*x

Parameters

  • x (Expression) The interpolation variable.
  • sample_points (Sequence[Expression | int]) The sample points used for interpolation.
  • values (Sequence[Polynomial]) The values associated with the sample points.

isolate_roots

Polynomial.isolate_roots(refine: float | Decimal | None = None) -> list[tuple[Expression, Expression, int]]

Isolate the real roots of the polynomial. The result is a list of intervals with rational bounds that contain exactly one root, and the multiplicity of that root. Optionally, the intervals can be refined to a given precision.

Examples

from symbolica import *
p = E('2016+5808*x+5452*x^2+1178*x^3+-753*x^4+-232*x^5+41*x^6').to_polynomial()
for a, b, n in p.isolate_roots():
    print('({},{}): {}'.format(a, b, n))

yields

(-56/45,-77/62): 1 (-98/79,-119/96): 1 (-119/96,-21/17): 1 (-7/6,0): 1 (0,6): 1 (6,12): 1

Parameters

  • refine (float | Decimal | None) The optional interval refinement tolerance.

lcoeff

Polynomial.lcoeff() -> Polynomial

Get the leading coefficient.

Examples

from symbolica import Expression as E
p = E('3x^2+6x+9').to_polynomial().lcoeff()
print(p)  # 3

monic

Polynomial.monic() -> Polynomial

Get the monic part of the polynomial, i.e., the polynomial divided by its leading coefficient.

Examples

from symbolica import Expression as E
p = E('6x^2+3x+9').to_polynomial()
print(p.monic())  # x^2+1/2*x+2/3

nterms

Polynomial.nterms() -> int

Get the number of terms in the polynomial.

parse

Polynomial.parse(
    input: str,
    vars: Sequence[str],
    default_namespace: str | None = None,
) -> Polynomial

Parse a polynomial with integer coefficients from a string. The input must be written in an expanded format and a list of all the variables must be provided.

If these requirements are too strict, use Expression.to_polynomial() or RationalPolynomial.parse() instead.

Examples

e = Polynomial.parse('3*x^2+y+y*4', ['x', 'y'])

Parameters

  • input (str) The input value.
  • vars (Sequence[str]) The variables treated as polynomial variables, in the given order.
  • default_namespace (str | None) The namespace assumed for unqualified symbols during parsing.

Raises

  • ValueError: If the input is not a valid Symbolica polynomial.

primitive

Polynomial.primitive() -> Polynomial

Get the primitive part of the polynomial, i.e., the polynomial with the content removed.

Examples

from symbolica import Expression as E
p = E('6x^2+3x+9').to_polynomial()
print(p.primitive())  # 2*x^2+x+3

quot_rem

Polynomial.quot_rem(rhs: Polynomial) -> tuple[Polynomial, Polynomial]

Divide self by rhs, returning the quotient and remainder.

Parameters

  • rhs (Polynomial) The right-hand-side operand.

reduce

Polynomial.reduce(gs: Sequence[Polynomial], grevlex: bool = True) -> Polynomial

Completely reduce the polynomial w.r.t the polynomials gs.

If grevlex=True, reverse graded lexicographical ordering is used, otherwise the ordering is lexicographical.

Examples

E('y^2+x').to_polynomial().reduce([E('x').to_polynomial()])

yields y^2

Parameters

  • gs (Sequence[Polynomial]) The polynomials that define the reducing set.
  • grevlex (bool) Whether graded reverse lexicographic ordering should be used.

reorder

Polynomial.reorder(vars: Sequence[Expression]) -> None

Reorder the polynomial in-place to use the given variable order.

Parameters

  • vars (Sequence[Expression]) The variables treated as polynomial variables, in the given order.

replace

Polynomial.replace(x: Expression, v: Polynomial | int) -> Polynomial

Replace the variable x with a polynomial v.

Examples

from symbolica import *
x = S('x')
p = E('x*y+2*x+x^2').to_polynomial()
r = E('y+1').to_polynomial())
p.replace(x, r)

Parameters

  • x (Expression) The variable to replace.
  • v (Polynomial | int) The polynomial or scalar value that should replace x.

resultant

Polynomial.resultant(rhs: Polynomial, var: Expression) -> Polynomial

Compute the resultant of two polynomials with respect to the variable var.

Parameters

  • rhs (Polynomial) The right-hand-side operand.
  • var (Expression) The variable with respect to which the resultant is computed.

simplify_algebraic_number

Polynomial.simplify_algebraic_number(min_poly: Polynomial) -> Polynomial

Find the minimal polynomial for the algebraic number represented by this polynomial expressed in the number field defined by minimal_poly.

Examples

from symbolica import *
(min_poly, rep2, rep23) = P('a^2-2').adjoin(P('b^2-3'))
rep2.simplify_algebraic_number(min_poly)

Yields b^2-2.

Parameters

  • min_poly (Polynomial) The minimal polynomial that defines the algebraic extension.

to_expression

Polynomial.to_expression() -> Expression

Convert the polynomial to an expression.

Examples

from symbolica import *
e = E('x*y+2*x+x^2')
p = e.to_polynomial()
print((e - p.to_expression()).expand())

to_finite_field

Polynomial.to_finite_field(prime: int) -> FiniteFieldPolynomial

Convert the coefficients of the polynomial to a finite field with prime prime.

Parameters

  • prime (int) The prime modulus of the target finite field.

to_latex

Polynomial.to_latex() -> str

Convert the polynomial into a LaTeX string.

to_number_field

Polynomial.to_number_field(min_poly: Polynomial) -> NumberFieldPolynomial

Convert the coefficients of the polynomial to a number field defined by the minimal polynomial min_poly.

Examples

from symbolica import *
a = P('a').to_number_field(P('a^2-2'))
print(a * a)  # 2

Parameters

  • min_poly (Polynomial) The minimal polynomial that defines the algebraic extension.