Polynomials Manipulation Module Reference

Polynomial manipulation algorithms and algebraic objects.

See Polynomial Manipulation for an index of documentation for the polys module and Basic functionality of the module for an introductory explanation.

Basic polynomial manipulation functions

sympy.polys.polytools.poly(expr, *gens, **args)[source]

Efficiently transform an expression into a polynomial.

Examples

>>> from sympy import poly
>>> from sympy.abc import x
>>> poly(x*(x**2 + x - 1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')
sympy.polys.polytools.poly_from_expr(expr, *gens, **args)[source]

Construct a polynomial from an expression.

sympy.polys.polytools.parallel_poly_from_expr(exprs, *gens, **args)[source]

Construct polynomials from expressions.

sympy.polys.polytools.degree(f, gen=0)[source]

Return the degree of f in the given variable.

The degree of 0 is negative infinity.

Examples

>>> from sympy import degree
>>> from sympy.abc import x, y
>>> degree(x**2 + y*x + 1, gen=x)
2
>>> degree(x**2 + y*x + 1, gen=y)
1
>>> degree(0, x)
-oo
sympy.polys.polytools.degree_list(f, *gens, **args)[source]

Return a list of degrees of f in all variables.

Examples

>>> from sympy import degree_list
>>> from sympy.abc import x, y
>>> degree_list(x**2 + y*x + 1)
(2, 1)
sympy.polys.polytools.LC(f, *gens, **args)[source]

Return the leading coefficient of f.

Examples

>>> from sympy import LC
>>> from sympy.abc import x, y
>>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y)
4
sympy.polys.polytools.LM(f, *gens, **args)[source]

Return the leading monomial of f.

Examples

>>> from sympy import LM
>>> from sympy.abc import x, y
>>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y)
x**2
sympy.polys.polytools.LT(f, *gens, **args)[source]

Return the leading term of f.

Examples

>>> from sympy import LT
>>> from sympy.abc import x, y
>>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y)
4*x**2
sympy.polys.polytools.pdiv(f, g, *gens, **args)[source]

Compute polynomial pseudo-division of f and g.

Examples

>>> from sympy import pdiv
>>> from sympy.abc import x
>>> pdiv(x**2 + 1, 2*x - 4)
(2*x + 4, 20)
sympy.polys.polytools.prem(f, g, *gens, **args)[source]

Compute polynomial pseudo-remainder of f and g.

Examples

>>> from sympy import prem
>>> from sympy.abc import x
>>> prem(x**2 + 1, 2*x - 4)
20
sympy.polys.polytools.pquo(f, g, *gens, **args)[source]

Compute polynomial pseudo-quotient of f and g.

Examples

>>> from sympy import pquo
>>> from sympy.abc import x
>>> pquo(x**2 + 1, 2*x - 4)
2*x + 4
>>> pquo(x**2 - 1, 2*x - 1)
2*x + 1
sympy.polys.polytools.pexquo(f, g, *gens, **args)[source]

Compute polynomial exact pseudo-quotient of f and g.

Examples

>>> from sympy import pexquo
>>> from sympy.abc import x
>>> pexquo(x**2 - 1, 2*x - 2)
2*x + 2
>>> pexquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
sympy.polys.polytools.div(f, g, *gens, **args)[source]

Compute polynomial division of f and g.

Examples

>>> from sympy import div, ZZ, QQ
>>> from sympy.abc import x
>>> div(x**2 + 1, 2*x - 4, domain=ZZ)
(0, x**2 + 1)
>>> div(x**2 + 1, 2*x - 4, domain=QQ)
(x/2 + 1, 5)
sympy.polys.polytools.rem(f, g, *gens, **args)[source]

Compute polynomial remainder of f and g.

Examples

>>> from sympy import rem, ZZ, QQ
>>> from sympy.abc import x
>>> rem(x**2 + 1, 2*x - 4, domain=ZZ)
x**2 + 1
>>> rem(x**2 + 1, 2*x - 4, domain=QQ)
5
sympy.polys.polytools.quo(f, g, *gens, **args)[source]

Compute polynomial quotient of f and g.

Examples

>>> from sympy import quo
>>> from sympy.abc import x
>>> quo(x**2 + 1, 2*x - 4)
x/2 + 1
>>> quo(x**2 - 1, x - 1)
x + 1
sympy.polys.polytools.exquo(f, g, *gens, **args)[source]

Compute polynomial exact quotient of f and g.

Examples

>>> from sympy import exquo
>>> from sympy.abc import x
>>> exquo(x**2 - 1, x - 1)
x + 1
>>> exquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
sympy.polys.polytools.half_gcdex(f, g, *gens, **args)[source]

Half extended Euclidean algorithm of f and g.

Returns (s, h) such that h = gcd(f, g) and s*f = h (mod g).

Examples

>>> from sympy import half_gcdex
>>> from sympy.abc import x
>>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(3/5 - x/5, x + 1)
sympy.polys.polytools.gcdex(f, g, *gens, **args)[source]

Extended Euclidean algorithm of f and g.

Returns (s, t, h) such that h = gcd(f, g) and s*f + t*g = h.

Examples

>>> from sympy import gcdex
>>> from sympy.abc import x
>>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1)
sympy.polys.polytools.invert(f, g, *gens, **args)[source]

Invert f modulo g when possible.

Examples

>>> from sympy import invert, S, mod_inverse
>>> from sympy.abc import x
>>> invert(x**2 - 1, 2*x - 1)
-4/3
>>> invert(x**2 - 1, x - 1)
Traceback (most recent call last):
...
NotInvertible: zero divisor

For more efficient inversion of Rationals, use the sympy.core.intfunc.mod_inverse function:

>>> mod_inverse(3, 5)
2
>>> (S(2)/5).invert(S(7)/3)
5/2
sympy.polys.polytools.subresultants(f, g, *gens, **args)[source]

Compute subresultant PRS of f and g.

Examples

>>> from sympy import subresultants
>>> from sympy.abc import x
>>> subresultants(x**2 + 1, x**2 - 1)
[x**2 + 1, x**2 - 1, -2]
sympy.polys.polytools.resultant(f, g, *gens, includePRS=False, **args)[source]

Compute resultant of f and g.

Examples

>>> from sympy import resultant
>>> from sympy.abc import x
>>> resultant(x**2 + 1, x**2 - 1)
4
sympy.polys.polytools.discriminant(f, *gens, **args)[source]

Compute discriminant of f.

Examples

>>> from sympy import discriminant
>>> from sympy.abc import x
>>> discriminant(x**2 + 2*x + 3)
-8
sympy.polys.polytools.terms_gcd(f, *gens, **args)[source]

Remove GCD of terms from f.

If the deep flag is True, then the arguments of f will have terms_gcd applied to them.

If a fraction is factored out of f and f is an Add, then an unevaluated Mul will be returned so that automatic simplification does not redistribute it. The hint clear, when set to False, can be used to prevent such factoring when all coefficients are not fractions.

Examples

>>> from sympy import terms_gcd, cos
>>> from sympy.abc import x, y
>>> terms_gcd(x**6*y**2 + x**3*y, x, y)
x**3*y*(x**3*y + 1)

The default action of polys routines is to expand the expression given to them. terms_gcd follows this behavior:

>>> terms_gcd((3+3*x)*(x+x*y))
3*x*(x*y + x + y + 1)

If this is not desired then the hint expand can be set to False. In this case the expression will be treated as though it were comprised of one or more terms:

>>> terms_gcd((3+3*x)*(x+x*y), expand=False)
(3*x + 3)*(x*y + x)

In order to traverse factors of a Mul or the arguments of other functions, the deep hint can be used:

>>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True)
3*x*(x + 1)*(y + 1)
>>> terms_gcd(cos(x + x*y), deep=True)
cos(x*(y + 1))

Rationals are factored out by default:

>>> terms_gcd(x + y/2)
(2*x + y)/2

Only the y-term had a coefficient that was a fraction; if one does not want to factor out the 1/2 in cases like this, the flag clear can be set to False:

>>> terms_gcd(x + y/2, clear=False)
x + y/2
>>> terms_gcd(x*y/2 + y**2, clear=False)
y*(x/2 + y)

The clear flag is ignored if all coefficients are fractions:

>>> terms_gcd(x/3 + y/2, clear=False)
(2*x + 3*y)/6
sympy.polys.polytools.cofactors(f, g, *gens, **args)[source]

Compute GCD and cofactors of f and g.

Returns polynomials (h, cff, cfg) such that h = gcd(f, g), and cff = quo(f, h) and cfg = quo(g, h) are, so called, cofactors of f and g.

Examples

>>> from sympy import cofactors
>>> from sympy.abc import x
>>> cofactors(x**2 - 1, x**2 - 3*x + 2)
(x - 1, x + 1, x - 2)
sympy.polys.polytools.gcd(f, g=None, *gens, **args)[source]

Compute GCD of f and g.

Examples

>>> from sympy import gcd
>>> from sympy.abc import x
>>> gcd(x**2 - 1, x**2 - 3*x + 2)
x - 1
sympy.polys.polytools.gcd_list(seq, *gens, **args)[source]

Compute GCD of a list of polynomials.

Examples

>>> from sympy import gcd_list
>>> from sympy.abc import x
>>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x - 1
sympy.polys.polytools.lcm(f, g=None, *gens, **args)[source]

Compute LCM of f and g.

Examples

>>> from sympy import lcm
>>> from sympy.abc import x
>>> lcm(x**2 - 1, x**2 - 3*x + 2)
x**3 - 2*x**2 - x + 2
sympy.polys.polytools.lcm_list(seq, *gens, **args)[source]

Compute LCM of a list of polynomials.

Examples

>>> from sympy import lcm_list
>>> from sympy.abc import x
>>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x**5 - x**4 - 2*x**3 - x**2 + x + 2
sympy.polys.polytools.trunc(f, p, *gens, **args)[source]

Reduce f modulo a constant p.

Examples

>>> from sympy import trunc
>>> from sympy.abc import x
>>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3)
-x**3 - x + 1
sympy.polys.polytools.monic(f, *gens, **args)[source]

Divide all coefficients of f by LC(f).

Examples

>>> from sympy import monic
>>> from sympy.abc import x
>>> monic(3*x**2 + 4*x + 2)
x**2 + 4*x/3 + 2/3
sympy.polys.polytools.content(f, *gens, **args)[source]

Compute GCD of coefficients of f.

Examples

>>> from sympy import content
>>> from sympy.abc import x
>>> content(6*x**2 + 8*x + 12)
2
sympy.polys.polytools.primitive(f, *gens, **args)[source]

Compute content and the primitive form of f.

Examples

>>> from sympy.polys.polytools import primitive
>>> from sympy.abc import x
>>> primitive(6*x**2 + 8*x + 12)
(2, 3*x**2 + 4*x + 6)
>>> eq = (2 + 2*x)*x + 2

Expansion is performed by default:

>>> primitive(eq)
(2, x**2 + x + 1)

Set expand to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction.

>>> primitive(eq, expand=False)
(1, x*(2*x + 2) + 2)
>>> eq.as_content_primitive()
(2, x*(x + 1) + 1)
sympy.polys.polytools.compose(f, g, *gens, **args)[source]

Compute functional composition f(g).

Examples

>>> from sympy import compose
>>> from sympy.abc import x
>>> compose(x**2 + x, x - 1)
x**2 - x
sympy.polys.polytools.decompose(f, *gens, **args)[source]

Compute functional decomposition of f.

Examples

>>> from sympy import decompose
>>> from sympy.abc import x
>>> decompose(x**4 + 2*x**3 - x - 1)
[x**2 - x - 1, x**2 + x]
sympy.polys.polytools.sturm(f, *gens, **args)[source]

Compute Sturm sequence of f.

Examples

>>> from sympy import sturm
>>> from sympy.abc import x
>>> sturm(x**3 - 2*x**2 + x - 3)
[x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4]
sympy.polys.polytools.gff_list(f, *gens, **args)[source]

Compute a list of greatest factorial factors of f.

Note that the input to ff() and rf() should be Poly instances to use the definitions here.

Examples

>>> from sympy import gff_list, ff, Poly
>>> from sympy.abc import x
>>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x)
>>> gff_list(f)
[(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]
>>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f
True
>>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 -         1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x)
>>> gff_list(f)
[(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)]
>>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f
True
sympy.polys.polytools.gff(f, *gens, **args)[source]

Compute greatest factorial factorization of f.

sympy.polys.polytools.sqf_norm(f, *gens, **args)[source]

Compute square-free norm of f.

Returns s, f, r, such that g(x) = f(x-sa) and r(x) = Norm(g(x)) is a square-free polynomial over K, where a is the algebraic extension of the ground domain.

Examples

>>> from sympy import sqf_norm, sqrt
>>> from sympy.abc import x
>>> sqf_norm(x**2 + 1, extension=[sqrt(3)])
([1], x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16)
sympy.polys.polytools.sqf_part(f, *gens, **args)[source]

Compute square-free part of f.

Examples

>>> from sympy import sqf_part
>>> from sympy.abc import x
>>> sqf_part(x**3 - 3*x - 2)
x**2 - x - 2
sympy.polys.polytools.sqf_list(f, *gens, **args)[source]

Compute a list of square-free factors of f.

Examples

>>> from sympy import sqf_list
>>> from sympy.abc import x
>>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
(2, [(x + 1, 2), (x + 2, 3)])
sympy.polys.polytools.sqf(f, *gens, **args)[source]

Compute square-free factorization of f.

Examples

>>> from sympy import sqf
>>> from sympy.abc import x
>>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
2*(x + 1)**2*(x + 2)**3
sympy.polys.polytools.factor_list(f, *gens, **args)[source]

Compute a list of irreducible factors of f.

Examples

>>> from sympy import factor_list
>>> from sympy.abc import x, y
>>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
(2, [(x + y, 1), (x**2 + 1, 2)])
sympy.polys.polytools.factor(f, *gens, deep=False, **args)[source]

Compute the factorization of expression, f, into irreducibles. (To factor an integer into primes, use factorint.)

There two modes implemented: symbolic and formal. If f is not an instance of Poly and generators are not specified, then the former mode is used. Otherwise, the formal mode is used.

In symbolic mode, factor() will traverse the expression tree and factor its components without any prior expansion, unless an instance of Add is encountered (in this case formal factorization is used). This way factor() can handle large or symbolic exponents.

By default, the factorization is computed over the rationals. To factor over other domain, e.g. an algebraic or finite field, use appropriate options: extension, modulus or domain.

Examples

>>> from sympy import factor, sqrt, exp
>>> from sympy.abc import x, y
>>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
2*(x + y)*(x**2 + 1)**2
>>> factor(x**2 + 1)
x**2 + 1
>>> factor(x**2 + 1, modulus=2)
(x + 1)**2
>>> factor(x**2 + 1, gaussian=True)
(x - I)*(x + I)
>>> factor(x**2 - 2, extension=sqrt(2))
(x - sqrt(2))*(x + sqrt(2))
>>> factor((x**2 - 1)/(x**2 + 4*x + 4))
(x - 1)*(x + 1)/(x + 2)**2
>>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1))
(x + 2)**20000000*(x**2 + 1)

By default, factor deals with an expression as a whole:

>>> eq = 2**(x**2 + 2*x + 1)
>>> factor(eq)
2**(x**2 + 2*x + 1)

If the deep flag is True then subexpressions will be factored:

>>> factor(eq, deep=True)
2**((x + 1)**2)

If the fraction flag is False then rational expressions will not be combined. By default it is True.

>>> factor(5*x + 3*exp(2 - 7*x), deep=True)
(5*x*exp(7*x) + 3*exp(2))*exp(-7*x)
>>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False)
5*x + 3*exp(2)*exp(-7*x)
sympy.polys.polytools.intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False)[source]

Compute isolating intervals for roots of f.

Examples

>>> from sympy import intervals
>>> from sympy.abc import x
>>> intervals(x**2 - 3)
[((-2, -1), 1), ((1, 2), 1)]
>>> intervals(x**2 - 3, eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]
sympy.polys.polytools.refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False)[source]

Refine an isolating interval of a root to the given precision.

Examples

>>> from sympy import refine_root
>>> from sympy.abc import x
>>> refine_root(x**2 - 3, 1, 2, eps=1e-2)
(19/11, 26/15)
sympy.polys.polytools.count_roots(f, inf=None, sup=None)[source]

Return the number of roots of f in [inf, sup] interval.

If one of inf or sup is complex, it will return the number of roots in the complex rectangle with corners at inf and sup.

Examples

>>> from sympy import count_roots, I
>>> from sympy.abc import x
>>> count_roots(x**4 - 4, -3, 3)
2
>>> count_roots(x**4 - 4, 0, 1 + 3*I)
1
sympy.polys.polytools.all_roots(f, multiple=True, radicals=True)[source]

Returns the real and complex roots of f with multiplicities.

Parameters:

f : Expr or Poly

A univariate polynomial with rational (or Float) coefficients.

multiple : bool (default True).

Whether to return a list of roots or a list of root/multiplicity pairs.

radicals : bool (default True)

Use simple radical formulae rather than ComplexRootOf for some irrational roots.

Returns:

A list of Expr (usually ComplexRootOf) representing

the roots is returned with each root repeated according to its multiplicity

as a root of f. The roots are always uniquely ordered with real roots

coming before complex roots. The real roots are in increasing order.

Complex roots are ordered by increasing real part and then increasing

imaginary part.

If multiple=False is passed then a list of root/multiplicity pairs is

returned instead.

If radicals=False is passed then all roots will be represented as

either rational numbers or ComplexRootOf.

Explanation

Finds all real and complex roots of a univariate polynomial with rational coefficients of any degree exactly. The roots are represented in the form given by rootof(). This is equivalent to using rootof() to find each of the indexed roots.

Examples

>>> from sympy import all_roots
>>> from sympy.abc import x, y
>>> print(all_roots(x**3 + 1))
[-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2]

Simple radical formulae are used in some cases but the cubic and quartic formulae are avoided. Instead most non-rational roots will be represented as ComplexRootOf:

>>> print(all_roots(x**3 + x + 1))
[CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)]

All roots of any polynomial with rational coefficients of any degree can be represented using ComplexRootOf. The use of ComplexRootOf bypasses limitations on the availability of radical formulae for quintic and higher degree polynomials _[1]:

>>> p = x**5 - x - 1
>>> for r in all_roots(p): print(r)
CRootOf(x**5 - x - 1, 0)
CRootOf(x**5 - x - 1, 1)
CRootOf(x**5 - x - 1, 2)
CRootOf(x**5 - x - 1, 3)
CRootOf(x**5 - x - 1, 4)
>>> [r.evalf(3) for r in all_roots(p)]
[1.17, -0.765 - 0.352*I, -0.765 + 0.352*I, 0.181 - 1.08*I, 0.181 + 1.08*I]

Irrational algebraic or transcendental coefficients cannot currently be handled by all_roots() (or rootof() more generally):

>>> from sympy import sqrt, expand
>>> p = expand((x - sqrt(2))*(x - sqrt(3)))
>>> print(p)
x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6)
>>> all_roots(p)
Traceback (most recent call last):
...
NotImplementedError: sorted roots not supported over EX

In the case of algebraic or transcendental coefficients ground_roots() might be able to find some roots by factorisation:

>>> from sympy import ground_roots
>>> ground_roots(p, x, extension=True)
{sqrt(2): 1, sqrt(3): 1}

If the coefficients are numeric then nroots() can be used to find all roots approximately:

>>> from sympy import nroots
>>> nroots(p, 5)
[1.4142, 1.732]

If the coefficients are symbolic then sympy.polys.polyroots.roots() or ground_roots() should be used instead:

>>> from sympy import roots, ground_roots
>>> p = x**2 - 3*x*y + 2*y**2
>>> roots(p, x)
{y: 1, 2*y: 1}
>>> ground_roots(p, x)
{y: 1, 2*y: 1}

See also

Poly.all_roots

The underlying Poly method used by all_roots().

rootof

Compute a single numbered root of a univariate polynomial.

real_roots

Compute all the real roots using rootof().

ground_roots

Compute some roots in the ground domain by factorisation.

nroots

Compute all roots using approximate numerical techniques.

sympy.polys.polyroots.roots

Compute symbolic expressions for roots using radical formulae.

References

sympy.polys.polytools.real_roots(f, multiple=True, radicals=True)[source]

Returns the real roots of f with multiplicities.

Parameters:

f : Expr or Poly

A univariate polynomial with rational (or Float) coefficients.

multiple : bool (default True).

Whether to return a list of roots or a list of root/multiplicity pairs.

radicals : bool (default True)

Use simple radical formulae rather than ComplexRootOf for some irrational roots.

Returns:

A list of Expr (usually ComplexRootOf) representing

the real roots is returned. The roots are arranged in increasing order and

are repeated according to their multiplicities as roots of f.

If multiple=False is passed then a list of root/multiplicity pairs is

returned instead.

If radicals=False is passed then all roots will be represented as

either rational numbers or ComplexRootOf.

Explanation

Finds all real roots of a univariate polynomial with rational coefficients of any degree exactly. The roots are represented in the form given by rootof(). This is equivalent to using rootof() or all_roots() and filtering out only the real roots. However if only the real roots are needed then real_roots() is more efficient than all_roots() because it computes only the real roots and avoids costly complex root isolation routines.

Examples

>>> from sympy import real_roots
>>> from sympy.abc import x, y
>>> real_roots(2*x**3 - 7*x**2 + 4*x + 4)
[-1/2, 2, 2]
>>> real_roots(2*x**3 - 7*x**2 + 4*x + 4, multiple=False)
[(-1/2, 1), (2, 2)]

Real roots of any polynomial with rational coefficients of any degree can be represented using ComplexRootOf:

>>> p = x**9 + 2*x + 2
>>> print(real_roots(p))
[CRootOf(x**9 + 2*x + 2, 0)]
>>> [r.evalf(3) for r in real_roots(p)]
[-0.865]

All rational roots will be returned as rational numbers. Roots of some simple factors will be expressed using radical or other formulae (unless radicals=False is passed). All other roots will be expressed as ComplexRootOf.

>>> p = (x + 7)*(x**2 - 2)*(x**3 + x + 1)
>>> print(real_roots(p))
[-7, -sqrt(2), CRootOf(x**3 + x + 1, 0), sqrt(2)]
>>> print(real_roots(p, radicals=False))
[-7, CRootOf(x**2 - 2, 0), CRootOf(x**3 + x + 1, 0), CRootOf(x**2 - 2, 1)]

All returned root expressions will numerically evaluate to real numbers with no imaginary part. This is in contrast to the expressions generated by the cubic or quartic formulae as used by roots() which suffer from casus irreducibilis [R809]:

>>> from sympy import roots
>>> p = 2*x**3 - 9*x**2 - 6*x + 3
>>> [r.evalf(5) for r in roots(p, multiple=True)]
[5.0365 - 0.e-11*I, 0.33984 + 0.e-13*I, -0.87636 + 0.e-10*I]
>>> [r.evalf(5) for r in real_roots(p, x)]
[-0.87636, 0.33984, 5.0365]
>>> [r.is_real for r in roots(p, multiple=True)]
[None, None, None]
>>> [r.is_real for r in real_roots(p)]
[True, True, True]

Using real_roots() is equivalent to using all_roots() (or rootof()) and filtering out only the real roots:

>>> from sympy import all_roots
>>> r = [r for r in all_roots(p) if r.is_real]
>>> real_roots(p) == r
True

If only the real roots are wanted then using real_roots() is faster than using all_roots(). Using real_roots() avoids complex root isolation which can be a lot slower than real root isolation especially for polynomials of high degree which typically have many more complex roots than real roots.

Irrational algebraic or transcendental coefficients cannot be handled by real_roots() (or rootof() more generally):

>>> from sympy import sqrt, expand
>>> p = expand((x - sqrt(2))*(x - sqrt(3)))
>>> print(p)
x**2 - sqrt(3)*x - sqrt(2)*x + sqrt(6)
>>> real_roots(p)
Traceback (most recent call last):
...
NotImplementedError: sorted roots not supported over EX

In the case of algebraic or transcendental coefficients ground_roots() might be able to find some roots by factorisation:

>>> from sympy import ground_roots
>>> ground_roots(p, x, extension=True)
{sqrt(2): 1, sqrt(3): 1}

If the coefficients are numeric then nroots() can be used to find all roots approximately:

>>> from sympy import nroots
>>> nroots(p, 5)
[1.4142, 1.732]

If the coefficients are symbolic then sympy.polys.polyroots.roots() or ground_roots() should be used instead.

>>> from sympy import roots, ground_roots
>>> p = x**2 - 3*x*y + 2*y**2
>>> roots(p, x)
{y: 1, 2*y: 1}
>>> ground_roots(p, x)
{y: 1, 2*y: 1}

See also

Poly.real_roots

The underlying Poly method used by real_roots().

rootof

Compute a single numbered root of a univariate polynomial.

all_roots

Compute all real and non-real roots using rootof().

ground_roots

Compute some roots in the ground domain by factorisation.

nroots

Compute all roots using approximate numerical techniques.

sympy.polys.polyroots.roots

Compute symbolic expressions for roots using radical formulae.

References

sympy.polys.polytools.nroots(f, n=15, maxsteps=50, cleanup=True)[source]

Compute numerical approximations of roots of f.

Examples

>>> from sympy import nroots
>>> from sympy.abc import x
>>> nroots(x**2 - 3, n=15)
[-1.73205080756888, 1.73205080756888]
>>> nroots(x**2 - 3, n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
sympy.polys.polytools.ground_roots(f, *gens, **args)[source]

Compute roots of f by factorization in the ground domain.

Examples

>>> from sympy import ground_roots
>>> from sympy.abc import x
>>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2)
{0: 2, 1: 2}
sympy.polys.polytools.nth_power_roots_poly(f, n, *gens, **args)[source]

Construct a polynomial with n-th powers of roots of f.

Examples

>>> from sympy import nth_power_roots_poly, factor, roots
>>> from sympy.abc import x
>>> f = x**4 - x**2 + 1
>>> g = factor(nth_power_roots_poly(f, 2))
>>> g
(x**2 - x + 1)**2
>>> R_f = [ (r**2).expand() for r in roots(f) ]
>>> R_g = roots(g).keys()
>>> set(R_f) == set(R_g)
True
sympy.polys.polytools.cancel(f, *gens, _signsimp=True, **args)[source]

Cancel common factors in a rational function f.

Examples

>>> from sympy import cancel, sqrt, Symbol, together
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1))
(2*x + 2)/(x - 1)
>>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A))
sqrt(6)/2

Note: due to automatic distribution of Rationals, a sum divided by an integer will appear as a sum. To recover a rational form use \(together\) on the result:

>>> cancel(x/2 + 1)
x/2 + 1
>>> together(_)
(x + 2)/2
sympy.polys.polytools.reduced(f, G, *gens, **args)[source]

Reduces a polynomial f modulo a set of polynomials G.

Given a polynomial f and a set of polynomials G = (g_1, ..., g_n), computes a set of quotients q = (q_1, ..., q_n) and the remainder r such that f = q_1*g_1 + ... + q_n*g_n + r, where r vanishes or r is a completely reduced polynomial with respect to G.

Examples

>>> from sympy import reduced
>>> from sympy.abc import x, y
>>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y])
([2*x, 1], x**2 + y**2 + y)
sympy.polys.polytools.groebner(F, *gens, **args)[source]

Computes the reduced Groebner basis for a set of polynomials.

Use the order argument to set the monomial ordering that will be used to compute the basis. Allowed orders are lex, grlex and grevlex. If no order is specified, it defaults to lex.

For more information on Groebner bases, see the references and the docstring of solve_poly_system().

Examples

Example taken from [1].

>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> F = [x*y - 2*y, 2*y**2 - x**2]
>>> groebner(F, x, y, order='lex')
GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y,
              domain='ZZ', order='lex')
>>> groebner(F, x, y, order='grlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
              domain='ZZ', order='grlex')
>>> groebner(F, x, y, order='grevlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
              domain='ZZ', order='grevlex')

By default, an improved implementation of the Buchberger algorithm is used. Optionally, an implementation of the F5B algorithm can be used. The algorithm can be set using the method flag or with the sympy.polys.polyconfig.setup() function.

>>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)]
>>> groebner(F, x, y, method='buchberger')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
>>> groebner(F, x, y, method='f5b')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')

References

  1. [Buchberger01]

  2. [Cox97]

sympy.polys.polytools.is_zero_dimensional(F, *gens, **args)[source]

Checks if the ideal generated by a Groebner basis is zero-dimensional.

The algorithm checks if the set of monomials not divisible by the leading monomial of any element of F is bounded.

References

David A. Cox, John B. Little, Donal O’Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230

class sympy.polys.polytools.Poly(rep, *gens, **args)[source]

Generic class for representing and operating on polynomial expressions.

See Polynomial Manipulation for general documentation.

Poly is a subclass of Basic rather than Expr but instances can be converted to Expr with the as_expr() method.

Deprecated since version 1.6: Combining Poly with non-Poly objects in binary operations is deprecated. Explicitly convert both objects to either Poly or Expr first. See Mixing Poly and non-polynomial expressions in binary operations.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y

Create a univariate polynomial:

>>> Poly(x*(x**2 + x - 1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')

Create a univariate polynomial with specific domain:

>>> from sympy import sqrt
>>> Poly(x**2 + 2*x + sqrt(3), domain='R')
Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR')

Create a multivariate polynomial:

>>> Poly(y*x**2 + x*y + 1)
Poly(x**2*y + x*y + 1, x, y, domain='ZZ')

Create a univariate polynomial, where y is a constant:

>>> Poly(y*x**2 + x*y + 1,x)
Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]')

You can evaluate the above polynomial as a function of y:

>>> Poly(y*x**2 + x*y + 1,x).eval(2)
6*y + 1
EC(order=None)[source]

Returns the last non-zero coefficient of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).EC()
3
EM(order=None)[source]

Returns the last non-zero monomial of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM()
x**0*y**1
ET(order=None)[source]

Returns the last non-zero term of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET()
(x**0*y**1, 3)
LC(order=None)[source]

Returns the leading coefficient of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC()
4
LM(order=None)[source]

Returns the leading monomial of f.

The Leading monomial signifies the monomial having the highest power of the principal generator in the expression f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM()
x**2*y**0
LT(order=None)[source]

Returns the leading term of f.

The Leading term signifies the term having the highest power of the principal generator in the expression f along with its coefficient.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT()
(x**2*y**0, 4)
TC()[source]

Returns the trailing coefficient of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).TC()
0
abs()[source]

Make all coefficients in f positive.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).abs()
Poly(x**2 + 1, x, domain='ZZ')
add(g)[source]

Add two polynomials f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).add(Poly(x - 2, x))
Poly(x**2 + x - 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x) + Poly(x - 2, x)
Poly(x**2 + x - 1, x, domain='ZZ')
add_ground(coeff)[source]

Add an element of the ground domain to f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).add_ground(2)
Poly(x + 3, x, domain='ZZ')
all_coeffs()[source]

Returns all coefficients from a univariate polynomial f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_coeffs()
[1, 0, 2, -1]
all_monoms()[source]

Returns all monomials from a univariate polynomial f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_monoms()
[(3,), (2,), (1,), (0,)]

See also

all_terms

all_roots(multiple=True, radicals=True)[source]

Return a list of real and complex roots with multiplicities.

See all_roots() for more explanation.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).all_roots()
[CRootOf(x**3 + x + 1, 0),
 CRootOf(x**3 + x + 1, 1),
 CRootOf(x**3 + x + 1, 2)]
all_terms()[source]

Returns all terms from a univariate polynomial f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_terms()
[((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)]
as_dict(native=False, zero=False)[source]

Switch to a dict representation.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict()
{(0, 1): -1, (1, 2): 2, (2, 0): 1}
as_expr(*gens)[source]

Convert a Poly instance to an Expr instance.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2 + 2*x*y**2 - y, x, y)
>>> f.as_expr()
x**2 + 2*x*y**2 - y
>>> f.as_expr({x: 5})
10*y**2 - y + 25
>>> f.as_expr(5, 6)
379
as_list(native=False)[source]

Switch to a list representation.

as_poly(*gens, **args)[source]

Converts self to a polynomial or returns None.

>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
cancel(g, include=False)[source]

Cancel common factors in a rational function f/g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x))
(1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True)
(Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
clear_denoms(convert=False)[source]

Clear denominators, but keep the ground domain.

Examples

>>> from sympy import Poly, S, QQ
>>> from sympy.abc import x
>>> f = Poly(x/2 + S(1)/3, x, domain=QQ)
>>> f.clear_denoms()
(6, Poly(3*x + 2, x, domain='QQ'))
>>> f.clear_denoms(convert=True)
(6, Poly(3*x + 2, x, domain='ZZ'))
coeff_monomial(monom)[source]

Returns the coefficient of monom in f if there, else None.

Examples

>>> from sympy import Poly, exp
>>> from sympy.abc import x, y
>>> p = Poly(24*x*y*exp(8) + 23*x, x, y)
>>> p.coeff_monomial(x)
23
>>> p.coeff_monomial(y)
0
>>> p.coeff_monomial(x*y)
24*exp(8)

Note that Expr.coeff() behaves differently, collecting terms if possible; the Poly must be converted to an Expr to use that method, however:

>>> p.as_expr().coeff(x)
24*y*exp(8) + 23
>>> p.as_expr().coeff(y)
24*x*exp(8)
>>> p.as_expr().coeff(x*y)
24*exp(8)

See also

nth

more efficient query using exponents of the monomial’s generators

coeffs(order=None)[source]

Returns all non-zero coefficients from f in lex order.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x + 3, x).coeffs()
[1, 2, 3]
cofactors(g)[source]

Returns the GCD of f and g and their cofactors.

Returns polynomials (h, cff, cfg) such that h = gcd(f, g), and cff = quo(f, h) and cfg = quo(g, h) are, so called, cofactors of f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x))
(Poly(x - 1, x, domain='ZZ'),
 Poly(x + 1, x, domain='ZZ'),
 Poly(x - 2, x, domain='ZZ'))
compose(g)[source]

Computes the functional composition of f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x, x).compose(Poly(x - 1, x))
Poly(x**2 - x, x, domain='ZZ')
content()[source]

Returns the GCD of polynomial coefficients.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(6*x**2 + 8*x + 12, x).content()
2
count_roots(inf=None, sup=None)[source]

Return the number of roots of f in [inf, sup] interval.

Examples

>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**4 - 4, x).count_roots(-3, 3)
2
>>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I)
1
decompose()[source]

Computes a functional decomposition of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose()
[Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')]
deflate()[source]

Reduce degree of f by mapping x_i**m to y_i.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate()
((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ'))
degree(gen=0)[source]

Returns degree of f in x_j.

The degree of 0 is negative infinity.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree()
2
>>> Poly(x**2 + y*x + y, x, y).degree(y)
1
>>> Poly(0, x).degree()
-oo
degree_list()[source]

Returns a list of degrees of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree_list()
(2, 1)
diff(*specs, **kwargs)[source]

Computes partial derivative of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).diff()
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1))
Poly(2*x*y, x, y, domain='ZZ')
discriminant()[source]

Computes the discriminant of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x + 3, x).discriminant()
-8
dispersion(g=None)[source]

Compute the dispersion of polynomials.

For two polynomials \(f(x)\) and \(g(x)\) with \(\deg f > 0\) and \(\deg g > 0\) the dispersion \(\operatorname{dis}(f, g)\) is defined as:

\[\begin{split}\operatorname{dis}(f, g) & := \max\{ J(f,g) \cup \{0\} \} \\ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}\end{split}\]

and for a single polynomial \(\operatorname{dis}(f) := \operatorname{dis}(f, f)\).

Examples

>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x

Dispersion set and dispersion of a simple polynomial:

>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6

Note that the definition of the dispersion is not symmetric:

>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo

Computing the dispersion also works over field extensions:

>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]

We can even perform the computations for polynomials having symbolic coefficients:

>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]

See also

dispersionset

References

  1. [ManWright94]

  2. [Koepf98]

  3. [Abramov71]

  4. [Man93]

dispersionset(g=None)[source]

Compute the dispersion set of two polynomials.

For two polynomials \(f(x)\) and \(g(x)\) with \(\deg f > 0\) and \(\deg g > 0\) the dispersion set \(\operatorname{J}(f, g)\) is defined as:

\[\begin{split}\operatorname{J}(f, g) & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}\end{split}\]

For a single polynomial one defines \(\operatorname{J}(f) := \operatorname{J}(f, f)\).

Examples

>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x

Dispersion set and dispersion of a simple polynomial:

>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6

Note that the definition of the dispersion is not symmetric:

>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo

Computing the dispersion also works over field extensions:

>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]

We can even perform the computations for polynomials having symbolic coefficients:

>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]

See also

dispersion

References

  1. [ManWright94]

  2. [Koepf98]

  3. [Abramov71]

  4. [Man93]

div(g, auto=True)[source]

Polynomial division with remainder of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x))
(Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ'))
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False)
(Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ'))
property domain

Get the ground domain of a Poly

Returns:

Domain:

Ground domain of the Poly.

Examples

>>> from sympy import Poly, Symbol
>>> x = Symbol('x')
>>> p = Poly(x**2 + x)
>>> p
Poly(x**2 + x, x, domain='ZZ')
>>> p.domain
ZZ
eject(*gens)[source]

Eject selected generators into the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
>>> f.eject(x)
Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
>>> f.eject(y)
Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
eval(x, a=None, auto=True)[source]

Evaluate f at a in the given variable.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x**2 + 2*x + 3, x).eval(2)
11
>>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2)
Poly(5*y + 8, y, domain='ZZ')
>>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)
>>> f.eval({x: 2})
Poly(5*y + 2*z + 6, y, z, domain='ZZ')
>>> f.eval({x: 2, y: 5})
Poly(2*z + 31, z, domain='ZZ')
>>> f.eval({x: 2, y: 5, z: 7})
45
>>> f.eval((2, 5))
Poly(2*z + 31, z, domain='ZZ')
>>> f(2, 5)
Poly(2*z + 31, z, domain='ZZ')
exclude()[source]

Remove unnecessary generators from f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import a, b, c, d, x
>>> Poly(a + x, a, b, c, d, x).exclude()
Poly(a + x, a, x, domain='ZZ')
exquo(g, auto=True)[source]

Computes polynomial exact quotient of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
exquo_ground(coeff)[source]

Exact quotient of f by a an element of the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).exquo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).exquo_ground(2)
Traceback (most recent call last):
...
ExactQuotientFailed: 2 does not divide 3 in ZZ
factor_list()[source]

Returns a list of irreducible factors of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list()
(2, [(Poly(x + y, x, y, domain='ZZ'), 1),
     (Poly(x**2 + 1, x, y, domain='ZZ'), 2)])
factor_list_include()[source]

Returns a list of irreducible factors of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list_include()
[(Poly(2*x + 2*y, x, y, domain='ZZ'), 1),
 (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]
property free_symbols

Free symbols of a polynomial expression.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x**2 + 1).free_symbols
{x}
>>> Poly(x**2 + y).free_symbols
{x, y}
>>> Poly(x**2 + y, x).free_symbols
{x, y}
>>> Poly(x**2 + y, x, z).free_symbols
{x, y}
property free_symbols_in_domain

Free symbols of the domain of self.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1).free_symbols_in_domain
set()
>>> Poly(x**2 + y).free_symbols_in_domain
set()
>>> Poly(x**2 + y, x).free_symbols_in_domain
{y}
classmethod from_dict(rep, *gens, **args)[source]

Construct a polynomial from a dict.

classmethod from_expr(rep, *gens, **args)[source]

Construct a polynomial from an expression.

classmethod from_list(rep, *gens, **args)[source]

Construct a polynomial from a list.

classmethod from_poly(rep, *gens, **args)[source]

Construct a polynomial from a polynomial.

galois_group(by_name=False, max_tries=30, randomize=False)[source]

Compute the Galois group of this polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**4 - 2)
>>> G, _ = f.galois_group(by_name=True)
>>> print(G)
S4TransitiveSubgroups.D4
gcd(g)[source]

Returns the polynomial GCD of f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x))
Poly(x - 1, x, domain='ZZ')
gcdex(g, auto=True)[source]

Extended Euclidean algorithm of f and g.

Returns (s, t, h) such that h = gcd(f, g) and s*f + t*g = h.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'),
 Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'),
 Poly(x + 1, x, domain='QQ'))
property gen

Return the principal generator.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).gen
x
get_domain()[source]

Get the ground domain of f.

get_modulus()[source]

Get the modulus of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, modulus=2).get_modulus()
2
gff_list()[source]

Computes greatest factorial factorization of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**5 + 2*x**4 - x**3 - 2*x**2
>>> Poly(f).gff_list()
[(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]
ground_roots()[source]

Compute roots of f by factorization in the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots()
{0: 2, 1: 2}
half_gcdex(g, auto=True)[source]

Half extended Euclidean algorithm of f and g.

Returns (s, h) such that h = gcd(f, g) and s*f = h (mod g).

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).half_gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ'))
has_only_gens(*gens)[source]

Return True if Poly(f, *gens) retains ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x*y + 1, x, y, z).has_only_gens(x, y)
True
>>> Poly(x*y + z, x, y, z).has_only_gens(x, y)
False
homogeneous_order()[source]

Returns the homogeneous order of f.

A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of f. If you only want to check if a polynomial is homogeneous, then use Poly.is_homogeneous().

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4)
>>> f.homogeneous_order()
5
homogenize(s)[source]

Returns the homogeneous polynomial of f.

A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you only want to check if a polynomial is homogeneous, then use Poly.is_homogeneous(). If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use Poly.homogeneous_order().

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3)
>>> f.homogenize(z)
Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ')
inject(front=False)[source]

Inject ground domain generators into f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x)
>>> f.inject()
Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ')
>>> f.inject(front=True)
Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ')
integrate(*specs, **args)[source]

Computes indefinite integral of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).integrate()
Poly(1/3*x**3 + x**2 + x, x, domain='QQ')
>>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0))
Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ')
intervals(all=False, eps=None, inf=None, sup=None, fast=False, sqf=False)[source]

Compute isolating intervals for roots of f.

For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).intervals()
[((-2, -1), 1), ((1, 2), 1)]
>>> Poly(x**2 - 3, x).intervals(eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]

References

invert(g, auto=True)[source]

Invert f modulo g when possible.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x))
Poly(-4/3, x, domain='QQ')
>>> Poly(x**2 - 1, x).invert(Poly(x - 1, x))
Traceback (most recent call last):
...
NotInvertible: zero divisor
property is_cyclotomic

Returns True if f is a cyclotomic polnomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
>>> Poly(f).is_cyclotomic
False
>>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
>>> Poly(g).is_cyclotomic
True
property is_ground

Returns True if f is an element of the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x, x).is_ground
False
>>> Poly(2, x).is_ground
True
>>> Poly(y, x).is_ground
True
property is_homogeneous

Returns True if f is a homogeneous polynomial.

A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use Poly.homogeneous_order().

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y, x, y).is_homogeneous
True
>>> Poly(x**3 + x*y, x, y).is_homogeneous
False
property is_irreducible

Returns True if f has no factors over its domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible
True
>>> Poly(x**2 + 1, x, modulus=2).is_irreducible
False
property is_linear

Returns True if f is linear in all its variables.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x + y + 2, x, y).is_linear
True
>>> Poly(x*y + 2, x, y).is_linear
False
property is_monic

Returns True if the leading coefficient of f is one.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 2, x).is_monic
True
>>> Poly(2*x + 2, x).is_monic
False
property is_monomial

Returns True if f is zero or has only one term.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(3*x**2, x).is_monomial
True
>>> Poly(3*x**2 + 1, x).is_monomial
False
property is_multivariate

Returns True if f is a multivariate polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_multivariate
False
>>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate
True
>>> Poly(x*y**2 + x*y + 1, x).is_multivariate
False
>>> Poly(x**2 + x + 1, x, y).is_multivariate
True
property is_one

Returns True if f is a unit polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_one
False
>>> Poly(1, x).is_one
True
property is_primitive

Returns True if GCD of the coefficients of f is one.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 6*x + 12, x).is_primitive
False
>>> Poly(x**2 + 3*x + 6, x).is_primitive
True
property is_quadratic

Returns True if f is quadratic in all its variables.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x*y + 2, x, y).is_quadratic
True
>>> Poly(x*y**2 + 2, x, y).is_quadratic
False
property is_sqf

Returns True if f is a square-free polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).is_sqf
False
>>> Poly(x**2 - 1, x).is_sqf
True
property is_univariate

Returns True if f is a univariate polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_univariate
True
>>> Poly(x*y**2 + x*y + 1, x, y).is_univariate
False
>>> Poly(x*y**2 + x*y + 1, x).is_univariate
True
>>> Poly(x**2 + x + 1, x, y).is_univariate
False
property is_zero

Returns True if f is a zero polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_zero
True
>>> Poly(1, x).is_zero
False
l1_norm()[source]

Returns l1 norm of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).l1_norm()
6
lcm(g)[source]

Returns polynomial LCM of f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x))
Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ')
length()[source]

Returns the number of non-zero terms in f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x - 1).length()
3
lift()[source]

Convert algebraic coefficients to rationals.

Examples

>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**2 + I*x + 1, x, extension=I).lift()
Poly(x**4 + 3*x**2 + 1, x, domain='QQ')
ltrim(gen)[source]

Remove dummy generators from f that are to the left of specified gen in the generators as ordered. When gen is an integer, it refers to the generator located at that position within the tuple of generators of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)
Poly(y**2 + y*z**2, y, z, domain='ZZ')
>>> Poly(z, x, y, z).ltrim(-1)
Poly(z, z, domain='ZZ')
make_monic_over_integers_by_scaling_roots()[source]

Turn any univariate polynomial over QQ or ZZ into a monic polynomial over ZZ, by scaling the roots as necessary.

Returns:

Pair (g, c)

g is the polynomial

c is the integer by which the roots had to be scaled

Explanation

This operation can be performed whether or not f is irreducible; when it is, this can be understood as determining an algebraic integer generating the same field as a root of f.

Examples

>>> from sympy import Poly, S
>>> from sympy.abc import x
>>> f = Poly(x**2/2 + S(1)/4 * x + S(1)/8, x, domain='QQ')
>>> f.make_monic_over_integers_by_scaling_roots()
(Poly(x**2 + 2*x + 4, x, domain='ZZ'), 4)
match(*args, **kwargs)[source]

Match expression from Poly. See Basic.match()

max_norm()[source]

Returns maximum norm of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).max_norm()
3
monic(auto=True)[source]

Divides all coefficients by LC(f).

Examples

>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic()
Poly(x**2 + 2*x + 3, x, domain='QQ')
>>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic()
Poly(x**2 + 4/3*x + 2/3, x, domain='QQ')
monoms(order=None)[source]

Returns all non-zero monomials from f in lex order.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms()
[(2, 0), (1, 2), (1, 1), (0, 1)]

See also

all_monoms

mul(g)[source]

Multiply two polynomials f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).mul(Poly(x - 2, x))
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x)*Poly(x - 2, x)
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
mul_ground(coeff)[source]

Multiply f by a an element of the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).mul_ground(2)
Poly(2*x + 2, x, domain='ZZ')
neg()[source]

Negate all coefficients in f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).neg()
Poly(-x**2 + 1, x, domain='ZZ')
>>> -Poly(x**2 - 1, x)
Poly(-x**2 + 1, x, domain='ZZ')
classmethod new(rep, *gens)[source]

Construct Poly instance from raw representation.

norm()[source]

Computes the product, Norm(f), of the conjugates of a polynomial f defined over a number field K.

Examples

>>> from sympy import Poly, sqrt
>>> from sympy.abc import x
>>> a, b = sqrt(2), sqrt(3)

A polynomial over a quadratic extension. Two conjugates x - a and x + a.

>>> f = Poly(x - a, x, extension=a)
>>> f.norm()
Poly(x**2 - 2, x, domain='QQ')

A polynomial over a quartic extension. Four conjugates x - a, x - a, x + a and x + a.

>>> f = Poly(x - a, x, extension=(a, b))
>>> f.norm()
Poly(x**4 - 4*x**2 + 4, x, domain='QQ')
nroots(n=15, maxsteps=50, cleanup=True)[source]

Compute numerical approximations of roots of f.

Parameters:

n … the number of digits to calculate

maxsteps … the maximum number of iterations to do

If the accuracy `n` cannot be reached in `maxsteps`, it will raise an

exception. You need to rerun with higher maxsteps.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3).nroots(n=15)
[-1.73205080756888, 1.73205080756888]
>>> Poly(x**2 - 3).nroots(n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
nth(*N)[source]

Returns the n-th coefficient of f where N are the exponents of the generators in the term of interest.

Examples

>>> from sympy import Poly, sqrt
>>> from sympy.abc import x, y
>>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2)
2
>>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2)
2
>>> Poly(4*sqrt(x)*y)
Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ')
>>> _.nth(1, 1)
4

See also

coeff_monomial

nth_power_roots_poly(n)[source]

Construct a polynomial with n-th powers of roots of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**4 - x**2 + 1)
>>> f.nth_power_roots_poly(2)
Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(3)
Poly(x**4 + 2*x**2 + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(4)
Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(12)
Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ')
property one

Return one polynomial with self’s properties.

pdiv(g)[source]

Polynomial pseudo-division of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x))
(Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ'))
per(rep, gens=None, remove=None)[source]

Create a Poly out of the given representation.

Examples

>>> from sympy import Poly, ZZ
>>> from sympy.abc import x, y
>>> from sympy.polys.polyclasses import DMP
>>> a = Poly(x**2 + 1)
>>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y])
Poly(y + 1, y, domain='ZZ')
pexquo(g)[source]

Polynomial exact pseudo-quotient of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
pow(n)[source]

Raise f to a non-negative power n.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).pow(3)
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
>>> Poly(x - 2, x)**3
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
pquo(g)[source]

Polynomial pseudo-quotient of f by g.

See the Caveat note in the function prem(f, g).

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x))
Poly(2*x + 4, x, domain='ZZ')
>>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
prem(g)[source]

Polynomial pseudo-remainder of f by g.

Caveat: The function prem(f, g, x) can be safely used to compute

in Z[x] _only_ subresultant polynomial remainder sequences (prs’s).

To safely compute Euclidean and Sturmian prs’s in Z[x] employ anyone of the corresponding functions found in the module sympy.polys.subresultants_qq_zz. The functions in the module with suffix _pg compute prs’s in Z[x] employing rem(f, g, x), whereas the functions with suffix _amv compute prs’s in Z[x] employing rem_z(f, g, x).

The function rem_z(f, g, x) differs from prem(f, g, x) in that to compute the remainder polynomials in Z[x] it premultiplies the divident times the absolute value of the leading coefficient of the divisor raised to the power degree(f, x) - degree(g, x) + 1.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x))
Poly(20, x, domain='ZZ')
primitive()[source]

Returns the content and a primitive form of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 8*x + 12, x).primitive()
(2, Poly(x**2 + 4*x + 6, x, domain='ZZ'))
quo(g, auto=True)[source]

Computes polynomial quotient of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x))
Poly(1/2*x + 1, x, domain='QQ')
>>> Poly(x**2 - 1, x).quo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
quo_ground(coeff)[source]

Quotient of f by a an element of the ground domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).quo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).quo_ground(2)
Poly(x + 1, x, domain='ZZ')
rat_clear_denoms(g)[source]

Clear denominators in a rational function f/g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2/y + 1, x)
>>> g = Poly(x**3 + y, x)
>>> p, q = f.rat_clear_denoms(g)
>>> p
Poly(x**2 + y, x, domain='ZZ[y]')
>>> q
Poly(y*x**3 + y**2, x, domain='ZZ[y]')
real_roots(multiple=True, radicals=True)[source]

Return a list of real roots with multiplicities.

See real_roots() for more explanation.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).real_roots()
[CRootOf(x**3 + x + 1, 0)]
refine_root(s, t, eps=None, steps=None, fast=False, check_sqf=False)[source]

Refine an isolating interval of a root to the given precision.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2)
(19/11, 26/15)
rem(g, auto=True)[source]

Computes the polynomial remainder of f by g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x))
Poly(5, x, domain='ZZ')
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False)
Poly(x**2 + 1, x, domain='ZZ')
reorder(*gens, **args)[source]

Efficiently apply new order of generators.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y**2, x, y).reorder(y, x)
Poly(y**2*x + x**2, y, x, domain='ZZ')
replace(x, y=None, **_ignore)[source]

Replace x with y in generators list.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1, x).replace(x, y)
Poly(y**2 + 1, y, domain='ZZ')
resultant(g, includePRS=False)[source]

Computes the resultant of f and g via PRS.

If includePRS=True, it includes the subresultant PRS in the result. Because the PRS is used to calculate the resultant, this is more efficient than calling subresultants() separately.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**2 + 1, x)
>>> f.resultant(Poly(x**2 - 1, x))
4
>>> f.resultant(Poly(x**2 - 1, x), includePRS=True)
(4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'),
     Poly(-2, x, domain='ZZ')])
retract(field=None)[source]

Recalculate the ground domain of a polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**2 + 1, x, domain='QQ[y]')
>>> f
Poly(x**2 + 1, x, domain='QQ[y]')
>>> f.retract()
Poly(x**2 + 1, x, domain='ZZ')
>>> f.retract(field=True)
Poly(x**2 + 1, x, domain='QQ')
revert(n)[source]

Compute f**(-1) mod x**n.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(1, x).revert(2)
Poly(1, x, domain='ZZ')
>>> Poly(1 + x, x).revert(1)
Poly(1, x, domain='ZZ')
>>> Poly(x**2 - 2, x).revert(2)
Traceback (most recent call last):
...
NotReversible: only units are reversible in a ring
>>> Poly(1/x, x).revert(1)
Traceback (most recent call last):
...
PolynomialError: 1/x contains an element of the generators set
root(index, radicals=True)[source]

Get an indexed root of a polynomial.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
>>> f.root(0)
-1/2
>>> f.root(1)
2
>>> f.root(2)
2
>>> f.root(3)
Traceback (most recent call last):
...
IndexError: root index out of [-3, 2] range, got 3
>>> Poly(x**5 + x + 1).root(0)
CRootOf(x**3 - x**2 + 1, 0)
same_root(a, b)[source]

Decide whether two roots of this polynomial are equal.

Raises:

DomainError

If the domain of the polynomial is not ZZ, QQ, RR, or CC.

MultivariatePolynomialError

If the polynomial is not univariate.

PolynomialError

If the polynomial is of degree < 2.

Examples

>>> from sympy import Poly, cyclotomic_poly, exp, I, pi
>>> f = Poly(cyclotomic_poly(5))
>>> r0 = exp(2*I*pi/5)
>>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)]
>>> print(indices)
[3]
set_domain(domain)[source]

Set the ground domain of f.

set_modulus(modulus)[source]

Set the modulus of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2)
Poly(x**2 + 1, x, modulus=2)
shift(a)[source]

Efficiently compute Taylor shift f(x + a).

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).shift(2)
Poly(x**2 + 2*x + 1, x, domain='ZZ')

See also

shift_list

Analogous method for multivariate polynomials.

shift_list(a)[source]

Efficiently compute Taylor shift f(X + A).

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x*y, [x,y]).shift_list([1, 2]) == Poly((x+1)*(y+2), [x,y])
True

See also

shift

Analogous method for univariate polynomials.

slice(x, m, n=None)[source]

Take a continuous subsequence of terms of f.

sqf_list(all=False)[source]

Returns a list of square-free factors of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16
>>> Poly(f).sqf_list()
(2, [(Poly(x + 1, x, domain='ZZ'), 2),
     (Poly(x + 2, x, domain='ZZ'), 3)])
>>> Poly(f).sqf_list(all=True)
(2, [(Poly(1, x, domain='ZZ'), 1),
     (Poly(x + 1, x, domain='ZZ'), 2),
     (Poly(x + 2, x, domain='ZZ'), 3)])
sqf_list_include(all=False)[source]

Returns a list of square-free factors of f.

Examples

>>> from sympy import Poly, expand
>>> from sympy.abc import x
>>> f = expand(2*(x + 1)**3*x**4)
>>> f
2*x**7 + 6*x**6 + 6*x**5 + 2*x**4
>>> Poly(f).sqf_list_include()
[(Poly(2, x, domain='ZZ'), 1),
 (Poly(x + 1, x, domain='ZZ'), 3),
 (Poly(x, x, domain='ZZ'), 4)]
>>> Poly(f).sqf_list_include(all=True)
[(Poly(2, x, domain='ZZ'), 1),
 (Poly(1, x, domain='ZZ'), 2),
 (Poly(x + 1, x, domain='ZZ'), 3),
 (Poly(x, x, domain='ZZ'), 4)]
sqf_norm()[source]

Computes square-free norm of f.

Returns s, f, r, such that g(x) = f(x-sa) and r(x) = Norm(g(x)) is a square-free polynomial over K, where a is the algebraic extension of the ground domain.

Examples

>>> from sympy import Poly, sqrt
>>> from sympy.abc import x
>>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm()
>>> s
[1]
>>> f
Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>')
>>> r
Poly(x**4 - 4*x**2 + 16, x, domain='QQ')
sqf_part()[source]

Computes square-free part of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 3*x - 2, x).sqf_part()
Poly(x**2 - x - 2, x, domain='ZZ')
sqr()[source]

Square a polynomial f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).sqr()
Poly(x**2 - 4*x + 4, x, domain='ZZ')
>>> Poly(x - 2, x)**2
Poly(x**2 - 4*x + 4, x, domain='ZZ')
sturm(auto=True)[source]

Computes the Sturm sequence of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 2*x**2 + x - 3, x).sturm()
[Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'),
 Poly(3*x**2 - 4*x + 1, x, domain='QQ'),
 Poly(2/9*x + 25/9, x, domain='QQ'),
 Poly(-2079/4, x, domain='QQ')]
sub(g)[source]

Subtract two polynomials f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).sub(Poly(x - 2, x))
Poly(x**2 - x + 3, x, domain='ZZ')
>>> Poly(x**2 + 1, x) - Poly(x - 2, x)
Poly(x**2 - x + 3, x, domain='ZZ')
sub_ground(coeff)[source]

Subtract an element of the ground domain from f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).sub_ground(2)
Poly(x - 1, x, domain='ZZ')
subresultants(g)[source]

Computes the subresultant PRS of f and g.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x))
[Poly(x**2 + 1, x, domain='ZZ'),
 Poly(x**2 - 1, x, domain='ZZ'),
 Poly(-2, x, domain='ZZ')]
terms(order=None)[source]

Returns all non-zero terms from f in lex order.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms()
[((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)]

See also

all_terms

terms_gcd()[source]

Remove GCD of terms from the polynomial f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd()
((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ'))
termwise(func, *gens, **args)[source]

Apply a function to all terms of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> def func(k, coeff):
...     k = k[0]
...     return coeff//10**(2-k)
>>> Poly(x**2 + 20*x + 400).termwise(func)
Poly(x**2 + 2*x + 4, x, domain='ZZ')
to_exact()[source]

Make the ground domain exact.

Examples

>>> from sympy import Poly, RR
>>> from sympy.abc import x
>>> Poly(x**2 + 1.0, x, domain=RR).to_exact()
Poly(x**2 + 1, x, domain='QQ')
to_field()[source]

Make the ground domain a field.

Examples

>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x, domain=ZZ).to_field()
Poly(x**2 + 1, x, domain='QQ')
to_ring()[source]

Make the ground domain a ring.

Examples

>>> from sympy import Poly, QQ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, domain=QQ).to_ring()
Poly(x**2 + 1, x, domain='ZZ')
total_degree()[source]

Returns the total degree of f.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).total_degree()
2
>>> Poly(x + y**5, x, y).total_degree()
5
transform(p, q)[source]

Efficiently evaluate the functional transformation q**n * f(p/q).

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x))
Poly(4, x, domain='ZZ')
trunc(p)[source]

Reduce f modulo a constant p.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3)
Poly(-x**3 - x + 1, x, domain='ZZ')
unify(g)[source]

Make f and g belong to the same domain.

Examples

>>> from sympy import Poly
>>> from sympy.abc import x
>>> f, g = Poly(x/2 + 1), Poly(2*x + 1)
>>> f
Poly(1/2*x + 1, x, domain='QQ')
>>> g
Poly(2*x + 1, x, domain='ZZ')
>>> F, G = f.unify(g)
>>> F
Poly(1/2*x + 1, x, domain='QQ')
>>> G
Poly(2*x + 1, x, domain='QQ')
property unit

Return unit polynomial with self’s properties.

property zero

Return zero polynomial with self’s properties.

class sympy.polys.polytools.PurePoly(rep, *gens, **args)[source]

Class for representing pure polynomials.

property free_symbols

Free symbols of a polynomial.

Examples

>>> from sympy import PurePoly
>>> from sympy.abc import x, y
>>> PurePoly(x**2 + 1).free_symbols
set()
>>> PurePoly(x**2 + y).free_symbols
set()
>>> PurePoly(x**2 + y, x).free_symbols
{y}
class sympy.polys.polytools.GroebnerBasis(F, *gens, **args)[source]

Represents a reduced Groebner basis.

contains(poly)[source]

Check if poly belongs the ideal generated by self.

Examples

>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> f = 2*x**3 + y**3 + 3*y
>>> G = groebner([x**2 + y**2 - 1, x*y - 2])
>>> G.contains(f)
True
>>> G.contains(f + 1)
False
fglm(order)[source]

Convert a Groebner basis from one ordering to another.

The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly.

Examples

>>> from sympy.abc import x, y
>>> from sympy import groebner
>>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
>>> G = groebner(F, x, y, order='grlex')
>>> list(G.fglm('lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
>>> list(groebner(F, x, y, order='lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]

References

[R810]

J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering

property is_zero_dimensional

Checks if the ideal generated by a Groebner basis is zero-dimensional.

The algorithm checks if the set of monomials not divisible by the leading monomial of any element of F is bounded.

References

David A. Cox, John B. Little, Donal O’Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230

reduce(expr, auto=True)[source]

Reduces a polynomial modulo a Groebner basis.

Given a polynomial f and a set of polynomials G = (g_1, ..., g_n), computes a set of quotients q = (q_1, ..., q_n) and the remainder r such that f = q_1*f_1 + ... + q_n*f_n + r, where r vanishes or r is a completely reduced polynomial with respect to G.

Examples

>>> from sympy import groebner, expand
>>> from sympy.abc import x, y
>>> f = 2*x**4 - x**2 + y**3 + y**2
>>> G = groebner([x**3 - x, y**3 - y])
>>> G.reduce(f)
([2*x, 1], x**2 + y**2 + y)
>>> Q, r = _
>>> expand(sum(q*g for q, g in zip(Q, G)) + r)
2*x**4 - x**2 + y**3 + y**2
>>> _ == f
True

Extra polynomial manipulation functions

sympy.polys.polyfuncs.symmetrize(F, *gens, **args)[source]

Rewrite a polynomial in terms of elementary symmetric polynomials.

A symmetric polynomial is a multivariate polynomial that remains invariant under any variable permutation, i.e., if \(f = f(x_1, x_2, \dots, x_n)\), then \(f = f(x_{i_1}, x_{i_2}, \dots, x_{i_n})\), where \((i_1, i_2, \dots, i_n)\) is a permutation of \((1, 2, \dots, n)\) (an element of the group \(S_n\)).

Returns a tuple of symmetric polynomials (f1, f2, ..., fn) such that f = f1 + f2 + ... + fn.

Examples

>>> from sympy.polys.polyfuncs import symmetrize
>>> from sympy.abc import x, y
>>> symmetrize(x**2 + y**2)
(-2*x*y + (x + y)**2, 0)
>>> symmetrize(x**2 + y**2, formal=True)
(s1**2 - 2*s2, 0, [(s1, x + y), (s2, x*y)])
>>> symmetrize(x**2 - y**2)
(-2*x*y + (x + y)**2, -2*y**2)
>>> symmetrize(x**2 - y**2, formal=True)
(s1**2 - 2*s2, -2*y**2, [(s1, x + y), (s2, x*y)])
sympy.polys.polyfuncs.horner(f, *gens, **args)[source]

Rewrite a polynomial in Horner form.

Among other applications, evaluation of a polynomial at a point is optimal when it is applied using the Horner scheme ([1]).

Examples

>>> from sympy.polys.polyfuncs import horner
>>> from sympy.abc import x, y, a, b, c, d, e
>>> horner(9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5)
x*(x*(x*(9*x + 8) + 7) + 6) + 5
>>> horner(a*x**4 + b*x**3 + c*x**2 + d*x + e)
e + x*(d + x*(c + x*(a*x + b)))
>>> f = 4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y
>>> horner(f, wrt=x)
x*(x*y*(4*y + 2) + y*(2*y + 1))
>>> horner(f, wrt=y)
y*(x*y*(4*x + 2) + x*(2*x + 1))

References

[1] - https://en.wikipedia.org/wiki/Horner_scheme

sympy.polys.polyfuncs.interpolate(data, x)[source]

Construct an interpolating polynomial for the data points evaluated at point x (which can be symbolic or numeric).

Examples

>>> from sympy.polys.polyfuncs import interpolate
>>> from sympy.abc import a, b, x

A list is interpreted as though it were paired with a range starting from 1:

>>> interpolate([1, 4, 9, 16], x)
x**2

This can be made explicit by giving a list of coordinates:

>>> interpolate([(1, 1), (2, 4), (3, 9)], x)
x**2

The (x, y) coordinates can also be given as keys and values of a dictionary (and the points need not be equispaced):

>>> interpolate([(-1, 2), (1, 2), (2, 5)], x)
x**2 + 1
>>> interpolate({-1: 2, 1: 2, 2: 5}, x)
x**2 + 1

If the interpolation is going to be used only once then the value of interest can be passed instead of passing a symbol:

>>> interpolate([1, 4, 9], 5)
25

Symbolic coordinates are also supported:

>>> [(i,interpolate((a, b), i)) for i in range(1, 4)]
[(1, a), (2, b), (3, -a + 2*b)]
sympy.polys.polyfuncs.viete(f, roots=None, *gens, **args)[source]

Generate Viete’s formulas for f.

Examples

>>> from sympy.polys.polyfuncs import viete
>>> from sympy import symbols
>>> x, a, b, c, r1, r2 = symbols('x,a:c,r1:3')
>>> viete(a*x**2 + b*x + c, [r1, r2], x)
[(r1 + r2, -b/a), (r1*r2, c/a)]

Domain constructors

sympy.polys.constructor.construct_domain(obj, **args)[source]

Construct a minimal domain for a list of expressions.

Parameters:

obj: list or dict

The expressions to build a domain for.

**args: keyword arguments

Options that affect the choice of domain.

Returns:

(K, elements): Domain and list of domain elements

The domain K that can represent the expressions and the list or dict of domain elements representing the same expressions as elements of K.

Explanation

Given a list of normal SymPy expressions (of type Expr) construct_domain will find a minimal Domain that can represent those expressions. The expressions will be converted to elements of the domain and both the domain and the domain elements are returned.

Examples

Given a list of Integer construct_domain will return the domain ZZ and a list of integers as elements of ZZ.

>>> from sympy import construct_domain, S
>>> expressions = [S(2), S(3), S(4)]
>>> K, elements = construct_domain(expressions)
>>> K
ZZ
>>> elements
[2, 3, 4]
>>> type(elements[0])  
<class 'int'>
>>> type(expressions[0])
<class 'sympy.core.numbers.Integer'>

If there are any Rational then QQ is returned instead.

>>> construct_domain([S(1)/2, S(3)/4])
(QQ, [1/2, 3/4])

If there are symbols then a polynomial ring K[x] is returned.

>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> construct_domain([2*x + 1, S(3)/4])
(QQ[x], [2*x + 1, 3/4])
>>> construct_domain([2*x + 1, y])
(ZZ[x,y], [2*x + 1, y])

If any symbols appear with negative powers then a rational function field K(x) will be returned.

>>> construct_domain([y/x, x/(1 - y)])
(ZZ(x,y), [y/x, -x/(y - 1)])

Irrational algebraic numbers will result in the EX domain by default. The keyword argument extension=True leads to the construction of an algebraic number field QQ<a>.

>>> from sympy import sqrt
>>> construct_domain([sqrt(2)])
(EX, [EX(sqrt(2))])
>>> construct_domain([sqrt(2)], extension=True)  
(QQ<sqrt(2)>, [ANP([1, 0], [1, 0, -2], QQ)])

See also

Domain, Expr

Monomials encoded as tuples

class sympy.polys.monomials.Monomial(monom, gens=None)[source]

Class representing a monomial, i.e. a product of powers.

as_expr(*gens)[source]

Convert a monomial instance to a SymPy expression.

gcd(other)[source]

Greatest common divisor of monomials.

lcm(other)[source]

Least common multiple of monomials.

sympy.polys.monomials.itermonomials(variables, max_degrees, min_degrees=None)[source]

max_degrees and min_degrees are either both integers or both lists. Unless otherwise specified, min_degrees is either 0 or [0, ..., 0].

A generator of all monomials monom is returned, such that either min_degree <= total_degree(monom) <= max_degree, or min_degrees[i] <= degree_list(monom)[i] <= max_degrees[i], for all i.

Case I. max_degrees And min_degrees Are Both Integers

Given a set of variables \(V\) and a min_degree \(N\) and a max_degree \(M\) generate a set of monomials of degree less than or equal to \(N\) and greater than or equal to \(M\). The total number of monomials in commutative variables is huge and is given by the following formula if \(M = 0\):

\[\frac{(\#V + N)!}{\#V! N!}\]

For example if we would like to generate a dense polynomial of a total degree \(N = 50\) and \(M = 0\), which is the worst case, in 5 variables, assuming that exponents and all of coefficients are 32-bit long and stored in an array we would need almost 80 GiB of memory! Fortunately most polynomials, that we will encounter, are sparse.

Consider monomials in commutative variables \(x\) and \(y\) and non-commutative variables \(a\) and \(b\):

>>> from sympy import symbols
>>> from sympy.polys.monomials import itermonomials
>>> from sympy.polys.orderings import monomial_key
>>> from sympy.abc import x, y

>>> sorted(itermonomials([x, y], 2), key=monomial_key('grlex', [y, x]))
[1, x, y, x**2, x*y, y**2]

>>> sorted(itermonomials([x, y], 3), key=monomial_key('grlex', [y, x]))
[1, x, y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3]

>>> a, b = symbols('a, b', commutative=False)
>>> set(itermonomials([a, b, x], 2))
{1, a, a**2, b, b**2, x, x**2, a*b, b*a, x*a, x*b}

>>> sorted(itermonomials([x, y], 2, 1), key=monomial_key('grlex', [y, x]))
[x, y, x**2, x*y, y**2]

Case Ii. max_degrees And min_degrees Are Both Lists

If max_degrees = [d_1, ..., d_n] and min_degrees = [e_1, ..., e_n], the number of monomials generated is:

\[(d_1 - e_1 + 1) (d_2 - e_2 + 1) \cdots (d_n - e_n + 1)\]

Let us generate all monomials monom in variables \(x\) and \(y\) such that [1, 2][i] <= degree_list(monom)[i] <= [2, 4][i], i = 0, 1

>>> from sympy import symbols
>>> from sympy.polys.monomials import itermonomials
>>> from sympy.polys.orderings import monomial_key
>>> from sympy.abc import x, y

>>> sorted(itermonomials([x, y], [2, 4], [1, 2]), reverse=True, key=monomial_key('lex', [x, y]))
[x**2*y**4, x**2*y**3, x**2*y**2, x*y**4, x*y**3, x*y**2]
sympy.polys.monomials.monomial_count(V, N)[source]

Computes the number of monomials.

The number of monomials is given by the following formula:

\[\frac{(\#V + N)!}{\#V! N!}\]

where \(N\) is a total degree and \(V\) is a set of variables.

Examples

>>> from sympy.polys.monomials import itermonomials, monomial_count
>>> from sympy.polys.orderings import monomial_key
>>> from sympy.abc import x, y
>>> monomial_count(2, 2)
6
>>> M = list(itermonomials([x, y], 2))
>>> sorted(M, key=monomial_key('grlex', [y, x]))
[1, x, y, x**2, x*y, y**2]
>>> len(M)
6

Orderings of monomials

class sympy.polys.orderings.MonomialOrder[source]

Base class for monomial orderings.

class sympy.polys.orderings.LexOrder[source]

Lexicographic order of monomials.

class sympy.polys.orderings.GradedLexOrder[source]

Graded lexicographic order of monomials.

class sympy.polys.orderings.ReversedGradedLexOrder[source]

Reversed graded lexicographic order of monomials.

Formal manipulation of roots of polynomials

sympy.polys.rootoftools.rootof(f, x, index=None, radicals=True, expand=True)[source]

An indexed root of a univariate polynomial.

Returns either a ComplexRootOf object or an explicit expression involving radicals.

Parameters:

f : Expr

Univariate polynomial.

x : Symbol, optional

Generator for f.

index : int or Integer

radicals : bool

Return a radical expression if possible.

expand : bool

Expand f.

class sympy.polys.rootoftools.RootOf(f, x, index=None, radicals=True, expand=True)[source]

Represents a root of a univariate polynomial.

Base class for roots of different kinds of polynomials. Only complex roots are currently supported.

class sympy.polys.rootoftools.ComplexRootOf(f, x, index=None, radicals=False, expand=True)[source]

Represents an indexed complex root of a polynomial.

Roots of a univariate polynomial separated into disjoint real or complex intervals and indexed in a fixed order:

  • real roots come first and are sorted in increasing order;

  • complex roots come next and are sorted primarily by increasing real part, secondarily by increasing imaginary part.

Currently only rational coefficients are allowed. Can be imported as CRootOf. To avoid confusion, the generator must be a Symbol.

Examples

>>> from sympy import CRootOf, rootof
>>> from sympy.abc import x

CRootOf is a way to reference a particular root of a polynomial. If there is a rational root, it will be returned:

>>> CRootOf.clear_cache()  # for doctest reproducibility
>>> CRootOf(x**2 - 4, 0)
-2

Whether roots involving radicals are returned or not depends on whether the radicals flag is true (which is set to True with rootof):

>>> CRootOf(x**2 - 3, 0)
CRootOf(x**2 - 3, 0)
>>> CRootOf(x**2 - 3, 0, radicals=True)
-sqrt(3)
>>> rootof(x**2 - 3, 0)
-sqrt(3)

The following cannot be expressed in terms of radicals:

>>> r = rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0); r
CRootOf(4*x**5 + 16*x**3 + 12*x**2 + 7, 0)

The root bounds can be seen, however, and they are used by the evaluation methods to get numerical approximations for the root.

>>> interval = r._get_interval(); interval
(-1, 0)
>>> r.evalf(2)
-0.98

The evalf method refines the width of the root bounds until it guarantees that any decimal approximation within those bounds will satisfy the desired precision. It then stores the refined interval so subsequent requests at or below the requested precision will not have to recompute the root bounds and will return very quickly.

Before evaluation above, the interval was

>>> interval
(-1, 0)

After evaluation it is now

>>> r._get_interval() 
(-165/169, -206/211)

To reset all intervals for a given polynomial, the _reset() method can be called from any CRootOf instance of the polynomial:

>>> r._reset()
>>> r._get_interval()
(-1, 0)

The eval_approx() method will also find the root to a given precision but the interval is not modified unless the search for the root fails to converge within the root bounds. And the secant method is used to find the root. (The evalf method uses bisection and will always update the interval.)

>>> r.eval_approx(2)
-0.98

The interval needed to be slightly updated to find that root:

>>> r._get_interval()
(-1, -1/2)

The evalf_rational will compute a rational approximation of the root to the desired accuracy or precision.

>>> r.eval_rational(n=2)
-69629/71318
>>> t = CRootOf(x**3 + 10*x + 1, 1)
>>> t.eval_rational(1e-1)
15/256 - 805*I/256
>>> t.eval_rational(1e-1, 1e-4)
3275/65536 - 414645*I/131072
>>> t.eval_rational(1e-4, 1e-4)
6545/131072 - 414645*I/131072
>>> t.eval_rational(n=2)
104755/2097152 - 6634255*I/2097152

Notes

Although a PurePoly can be constructed from a non-symbol generator RootOf instances of non-symbols are disallowed to avoid confusion over what root is being represented.

>>> from sympy import exp, PurePoly
>>> PurePoly(x) == PurePoly(exp(x))
True
>>> CRootOf(x - 1, 0)
1
>>> CRootOf(exp(x) - 1, 0)  # would correspond to x == 0
Traceback (most recent call last):
...
sympy.polys.polyerrors.PolynomialError: generator must be a Symbol
classmethod _all_roots(poly, use_cache=True)[source]

Get real and complex roots of a composite polynomial.

classmethod _complexes_index(complexes, index)[source]

Map initial complex root index to an index in a factor where the root belongs.

classmethod _complexes_sorted(complexes)[source]

Make complex isolating intervals disjoint and sort roots.

classmethod _count_roots(roots)[source]

Count the number of real or complex roots with multiplicities.

_ensure_complexes_init()[source]

Ensure that our poly has entries in the complexes cache.

_ensure_reals_init()[source]

Ensure that our poly has entries in the reals cache.

_eval_evalf(prec, **kwargs)[source]

Evaluate this complex root to the given precision.

_eval_is_imaginary()[source]

Return True if the root is imaginary.

_eval_is_real()[source]

Return True if the root is real.

classmethod _get_complexes(factors, use_cache=True)[source]

Compute complex root isolating intervals for a list of factors.

classmethod _get_complexes_sqf(currentfactor, use_cache=True)[source]

Get complex root isolating intervals for a square-free factor.

_get_interval()[source]

Internal function for retrieving isolation interval from cache.

classmethod _get_reals(factors, use_cache=True)[source]

Compute real root isolating intervals for a list of factors.

classmethod _get_reals_sqf(currentfactor, use_cache=True)[source]

Get real root isolating intervals for a square-free factor.

classmethod _get_roots(method, poly, radicals)[source]

Return postprocessed roots of specified kind.

classmethod _indexed_root(poly, index, lazy=False)[source]

Get a root of a composite polynomial by index.

classmethod _new(poly, index)[source]

Construct new CRootOf object from raw data.

classmethod _postprocess_root(root, radicals)[source]

Return the root if it is trivial or a CRootOf object.

classmethod _preprocess_roots(poly)[source]

Take heroic measures to make poly compatible with CRootOf.

classmethod _real_roots(poly)[source]

Get real roots of a composite polynomial.

classmethod _reals_index(reals, index)[source]

Map initial real root index to an index in a factor where the root belongs.

classmethod _reals_sorted(reals)[source]

Make real isolating intervals disjoint and sort roots.

classmethod _refine_complexes(complexes)[source]

return complexes such that no bounding rectangles of non-conjugate roots would intersect. In addition, assure that neither ay nor by is 0 to guarantee that non-real roots are distinct from real roots in terms of the y-bounds.

_reset()[source]

Reset all intervals

classmethod _roots_trivial(poly, radicals)[source]

Compute roots in linear, quadratic and binomial cases.

_set_interval(interval)[source]

Internal function for updating isolation interval in cache.

classmethod all_roots(poly, radicals=True)[source]

Get real and complex roots of a polynomial.

classmethod clear_cache()[source]

Reset cache for reals and complexes.

The intervals used to approximate a root instance are updated as needed. When a request is made to see the intervals, the most current values are shown. \(clear_cache\) will reset all CRootOf instances back to their original state.

See also

_reset

eval_approx(n, return_mpmath=False)[source]

Evaluate this complex root to the given precision.

This uses secant method and root bounds are used to both generate an initial guess and to check that the root returned is valid. If ever the method converges outside the root bounds, the bounds will be made smaller and updated.

eval_rational(dx=None, dy=None, n=15)[source]

Return a Rational approximation of self that has real and imaginary component approximations that are within dx and dy of the true values, respectively. Alternatively, n digits of precision can be specified.

The interval is refined with bisection and is sure to converge. The root bounds are updated when the refinement is complete so recalculation at the same or lesser precision will not have to repeat the refinement and should be much faster.

The following example first obtains Rational approximation to 1e-8 accuracy for all roots of the 4-th order Legendre polynomial. Since the roots are all less than 1, this will ensure the decimal representation of the approximation will be correct (including rounding) to 6 digits:

>>> from sympy import legendre_poly, Symbol
>>> x = Symbol("x")
>>> p = legendre_poly(4, x, polys=True)
>>> r = p.real_roots()[-1]
>>> r.eval_rational(10**-8).n(6)
0.861136

It is not necessary to a two-step calculation, however: the decimal representation can be computed directly:

>>> r.evalf(17)
0.86113631159405258
classmethod real_roots(poly, radicals=True)[source]

Get real roots of a polynomial.

class sympy.polys.rootoftools.RootSum(expr, func=None, x=None, auto=True, quadratic=False)[source]

Represents a sum of all roots of a univariate polynomial.

classmethod new(poly, func, auto=True)[source]

Construct new RootSum instance.

Symbolic root-finding algorithms

sympy.polys.polyroots.roots(f, *gens, auto=True, cubics=True, trig=False, quartics=True, quintics=False, multiple=False, filter=None, predicate=None, strict=False, **flags)[source]

Computes symbolic roots of a univariate polynomial.

Given a univariate polynomial f with symbolic coefficients (or a list of the polynomial’s coefficients), returns a dictionary with its roots and their multiplicities.

Only roots expressible via radicals will be returned. To get a complete set of roots use RootOf class or numerical methods instead. By default cubic and quartic formulas are used in the algorithm. To disable them because of unreadable output set cubics=False or quartics=False respectively. If cubic roots are real but are expressed in terms of complex numbers (casus irreducibilis [1]) the trig flag can be set to True to have the solutions returned in terms of cosine and inverse cosine functions.

To get roots from a specific domain set the filter flag with one of the following specifiers: Z, Q, R, I, C. By default all roots are returned (this is equivalent to setting filter='C').

By default a dictionary is returned giving a compact result in case of multiple roots. However to get a list containing all those roots set the multiple flag to True; the list will have identical roots appearing next to each other in the result. (For a given Poly, the all_roots method will give the roots in sorted numerical order.)

If the strict flag is True, UnsolvableFactorError will be raised if the roots found are known to be incomplete (because some roots are not expressible in radicals).

Examples

>>> from sympy import Poly, roots, degree
>>> from sympy.abc import x, y
>>> roots(x**2 - 1, x)
{-1: 1, 1: 1}
>>> p = Poly(x**2-1, x)
>>> roots(p)
{-1: 1, 1: 1}
>>> p = Poly(x**2-y, x, y)
>>> roots(Poly(p, x))
{-sqrt(y): 1, sqrt(y): 1}
>>> roots(x**2 - y, x)
{-sqrt(y): 1, sqrt(y): 1}
>>> roots([1, 0, -1])
{-1: 1, 1: 1}

roots will only return roots expressible in radicals. If the given polynomial has some or all of its roots inexpressible in radicals, the result of roots will be incomplete or empty respectively.

Example where result is incomplete:

>>> roots((x-1)*(x**5-x+1), x)
{1: 1}

In this case, the polynomial has an unsolvable quintic factor whose roots cannot be expressed by radicals. The polynomial has a rational root (due to the factor \((x-1)\)), which is returned since roots always finds all rational roots.

Example where result is empty:

>>> roots(x**7-3*x**2+1, x)
{}

Here, the polynomial has no roots expressible in radicals, so roots returns an empty dictionary.

The result produced by roots is complete if and only if the sum of the multiplicity of each root is equal to the degree of the polynomial. If strict=True, UnsolvableFactorError will be raised if the result is incomplete.

The result can be be checked for completeness as follows:

>>> f = x**3-2*x**2+1
>>> sum(roots(f, x).values()) == degree(f, x)
True
>>> f = (x-1)*(x**5-x+1)
>>> sum(roots(f, x).values()) == degree(f, x)
False

References

Special polynomials

sympy.polys.specialpolys.swinnerton_dyer_poly(n, x=None, polys=False)[source]

Generates n-th Swinnerton-Dyer polynomial in \(x\).

Parameters:

n : int

\(n\) decides the order of polynomial

x : optional

polys : bool, optional

polys=True returns an expression, otherwise (default) returns an expression.

sympy.polys.specialpolys.interpolating_poly(n, x, X='x', Y='y')[source]

Construct Lagrange interpolating polynomial for n data points. If a sequence of values are given for X and Y then the first n values will be used.

sympy.polys.specialpolys.cyclotomic_poly(n, x=None, polys=False)[source]

Generates cyclotomic polynomial of order \(n\) in \(x\).

Parameters:

n : int

\(n\) decides the order of polynomial

x : optional

polys : bool, optional

polys=True returns an expression, otherwise (default) returns an expression.

sympy.polys.specialpolys.symmetric_poly(n, *gens, polys=False)[source]

Generates symmetric polynomial of order \(n\).

Parameters:

polys: bool, optional (default: False)

Returns a Poly object when polys=True, otherwise (default) returns an expression.

sympy.polys.specialpolys.random_poly(x, n, inf, sup, domain=ZZ, polys=False)[source]

Generates a polynomial of degree n with coefficients in [inf, sup].

Parameters:

x

\(x\) is the independent term of polynomial

n : int

\(n\) decides the order of polynomial

inf

Lower limit of range in which coefficients lie

sup

Upper limit of range in which coefficients lie

domain : optional

Decides what ring the coefficients are supposed to belong. Default is set to Integers.

polys : bool, optional

polys=True returns an expression, otherwise (default) returns an expression.

Orthogonal polynomials

sympy.polys.orthopolys.chebyshevt_poly(n, x=None, polys=False)[source]

Generates the Chebyshev polynomial of the first kind \(T_n(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.chebyshevu_poly(n, x=None, polys=False)[source]

Generates the Chebyshev polynomial of the second kind \(U_n(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.gegenbauer_poly(n, a, x=None, polys=False)[source]

Generates the Gegenbauer polynomial \(C_n^{(a)}(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

a

Decides minimal domain for the list of coefficients.

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.hermite_poly(n, x=None, polys=False)[source]

Generates the Hermite polynomial \(H_n(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.hermite_prob_poly(n, x=None, polys=False)[source]

Generates the probabilist’s Hermite polynomial \(He_n(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.jacobi_poly(n, a, b, x=None, polys=False)[source]

Generates the Jacobi polynomial \(P_n^{(a,b)}(x)\).

Parameters:

n : int

Degree of the polynomial.

a

Lower limit of minimal domain for the list of coefficients.

b

Upper limit of minimal domain for the list of coefficients.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.legendre_poly(n, x=None, polys=False)[source]

Generates the Legendre polynomial \(P_n(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.laguerre_poly(n, x=None, alpha=0, polys=False)[source]

Generates the Laguerre polynomial \(L_n^{(\alpha)}(x)\).

Parameters:

n : int

Degree of the polynomial.

x : optional

alpha : optional

Decides minimal domain for the list of coefficients.

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.orthopolys.spherical_bessel_fn(n, x=None, polys=False)[source]

Coefficients for the spherical Bessel functions.

These are only needed in the jn() function.

The coefficients are calculated from:

fn(0, z) = 1/z fn(1, z) = 1/z**2 fn(n-1, z) + fn(n+1, z) == (2*n+1)/z * fn(n, z)

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

Examples

>>> from sympy.polys.orthopolys import spherical_bessel_fn as fn
>>> from sympy import Symbol
>>> z = Symbol("z")
>>> fn(1, z)
z**(-2)
>>> fn(2, z)
-1/z + 3/z**3
>>> fn(3, z)
-6/z**2 + 15/z**4
>>> fn(4, z)
1/z - 45/z**3 + 105/z**5

Appell sequences

sympy.polys.appellseqs.bernoulli_poly(n, x=None, polys=False)[source]

Generates the Bernoulli polynomial \(\operatorname{B}_n(x)\).

\(\operatorname{B}_n(x)\) is the unique polynomial satisfying

\[\int_{x}^{x+1} \operatorname{B}_n(t) \,dt = x^n.\]

Based on this, we have for nonnegative integer \(s\) and integer \(a\) and \(b\)

\[\sum_{k=a}^{b} k^s = \frac{\operatorname{B}_{s+1}(b+1) - \operatorname{B}_{s+1}(a)}{s+1}\]

which is related to Jakob Bernoulli’s original motivation for introducing the Bernoulli numbers, the values of these polynomials at \(x = 1\).

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

Examples

>>> from sympy import summation
>>> from sympy.abc import x
>>> from sympy.polys import bernoulli_poly
>>> bernoulli_poly(5, x)
x**5 - 5*x**4/2 + 5*x**3/3 - x/6
>>> def psum(p, a, b):
...     return (bernoulli_poly(p+1,b+1) - bernoulli_poly(p+1,a)) / (p+1)
>>> psum(4, -6, 27)
3144337
>>> summation(x**4, (x, -6, 27))
3144337
>>> psum(1, 1, x).factor()
x*(x + 1)/2
>>> psum(2, 1, x).factor()
x*(x + 1)*(2*x + 1)/6
>>> psum(3, 1, x).factor()
x**2*(x + 1)**2/4

References

sympy.polys.appellseqs.bernoulli_c_poly(n, x=None, polys=False)[source]

Generates the central Bernoulli polynomial \(\operatorname{B}_n^c(x)\).

These are scaled and shifted versions of the plain Bernoulli polynomials, done in such a way that \(\operatorname{B}_n^c(x)\) is an even or odd function for even or odd \(n\) respectively:

\[\operatorname{B}_n^c(x) = 2^n \operatorname{B}_n \left(\frac{x+1}{2}\right)\]
Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.appellseqs.genocchi_poly(n, x=None, polys=False)[source]

Generates the Genocchi polynomial \(\operatorname{G}_n(x)\).

\(\operatorname{G}_n(x)\) is twice the difference between the plain and central Bernoulli polynomials, so has degree \(n-1\):

\[\operatorname{G}_n(x) = 2 (\operatorname{B}_n(x) - \operatorname{B}_n^c(x))\]

The factor of 2 in the definition endows \(\operatorname{G}_n(x)\) with integer coefficients.

Parameters:

n : int

Degree of the polynomial plus one.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.appellseqs.euler_poly(n, x=None, polys=False)[source]

Generates the Euler polynomial \(\operatorname{E}_n(x)\).

These are scaled and reindexed versions of the Genocchi polynomials:

\[\operatorname{E}_n(x) = -\frac{\operatorname{G}_{n+1}(x)}{n+1}\]
Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

sympy.polys.appellseqs.andre_poly(n, x=None, polys=False)[source]

Generates the Andre polynomial \(\mathcal{A}_n(x)\).

This is the Appell sequence where the constant coefficients form the sequence of Euler numbers euler(n). As such they have integer coefficients and parities matching the parity of \(n\).

Luschny calls these the Swiss-knife polynomials because their values at 0 and 1 can be simply transformed into both the Bernoulli and Euler numbers. Here they are called the Andre polynomials because \(|\mathcal{A}_n(n\bmod 2)|\) for \(n \ge 0\) generates what Luschny calls the Andre numbers, A000111 in the OEIS.

Parameters:

n : int

Degree of the polynomial.

x : optional

polys : bool, optional

If True, return a Poly, otherwise (default) return an expression.

Examples

>>> from sympy import bernoulli, euler, genocchi
>>> from sympy.abc import x
>>> from sympy.polys import andre_poly
>>> andre_poly(9, x)
x**9 - 36*x**7 + 630*x**5 - 5124*x**3 + 12465*x
>>> [andre_poly(n, 0) for n in range(11)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
>>> [euler(n) for n in range(11)]
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0, -50521]
>>> [andre_poly(n-1, 1) * n / (4**n - 2**n) for n in range(1, 11)]
[1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> [bernoulli(n) for n in range(1, 11)]
[1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> [-andre_poly(n-1, -1) * n / (-2)**(n-1) for n in range(1, 11)]
[-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
>>> [genocchi(n) for n in range(1, 11)]
[-1, -1, 0, 1, 0, -3, 0, 17, 0, -155]
>>> [abs(andre_poly(n, n%2)) for n in range(11)]
[1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]

References

[R813]

Peter Luschny, “An introduction to the Bernoulli function”, https://arxiv.org/abs/2009.06743

Manipulation of rational functions

sympy.polys.rationaltools.together(expr, deep=False, fraction=True)[source]

Denest and combine rational expressions using symbolic methods.

This function takes an expression or a container of expressions and puts it (them) together by denesting and combining rational subexpressions. No heroic measures are taken to minimize degree of the resulting numerator and denominator. To obtain completely reduced expression use cancel(). However, together() can preserve as much as possible of the structure of the input expression in the output (no expansion is performed).

A wide variety of objects can be put together including lists, tuples, sets, relational objects, integrals and others. It is also possible to transform interior of function applications, by setting deep flag to True.

By definition, together() is a complement to apart(), so apart(together(expr)) should return expr unchanged. Note however, that together() uses only symbolic methods, so it might be necessary to use cancel() to perform algebraic simplification and minimize degree of the numerator and denominator.

Examples

>>> from sympy import together, exp
>>> from sympy.abc import x, y, z
>>> together(1/x + 1/y)
(x + y)/(x*y)
>>> together(1/x + 1/y + 1/z)
(x*y + x*z + y*z)/(x*y*z)
>>> together(1/(x*y) + 1/y**2)
(x + y)/(x*y**2)
>>> together(1/(1 + 1/x) + 1/(1 + 1/y))
(x*(y + 1) + y*(x + 1))/((x + 1)*(y + 1))
>>> together(exp(1/x + 1/y))
exp(1/y + 1/x)
>>> together(exp(1/x + 1/y), deep=True)
exp((x + y)/(x*y))
>>> together(1/exp(x) + 1/(x*exp(x)))
(x + 1)*exp(-x)/x
>>> together(1/exp(2*x) + 1/(x*exp(3*x)))
(x*exp(x) + 1)*exp(-3*x)/x

Partial fraction decomposition

sympy.polys.partfrac.apart(f, x=None, full=False, **options)[source]

Compute partial fraction decomposition of a rational function.

Given a rational function f, computes the partial fraction decomposition of f. Two algorithms are available: One is based on the undertermined coefficients method, the other is Bronstein’s full partial fraction decomposition algorithm.

The undetermined coefficients method (selected by full=False) uses polynomial factorization (and therefore accepts the same options as factor) for the denominator. Per default it works over the rational numbers, therefore decomposition of denominators with non-rational roots (e.g. irrational, complex roots) is not supported by default (see options of factor).

Bronstein’s algorithm can be selected by using full=True and allows a decomposition of denominators with non-rational roots. A human-readable result can be obtained via doit() (see examples below).

Examples

>>> from sympy.polys.partfrac import apart
>>> from sympy.abc import x, y

By default, using the undetermined coefficients method:

>>> apart(y/(x + 2)/(x + 1), x)
-y/(x + 2) + y/(x + 1)

The undetermined coefficients method does not provide a result when the denominators roots are not rational:

>>> apart(y/(x**2 + x + 1), x)
y/(x**2 + x + 1)

You can choose Bronstein’s algorithm by setting full=True:

>>> apart(y/(x**2 + x + 1), x, full=True)
RootSum(_w**2 + _w + 1, Lambda(_a, (-2*_a*y/3 - y/3)/(-_a + x)))

Calling doit() yields a human-readable result:

>>> apart(y/(x**2 + x + 1), x, full=True).doit()
(-y/3 - 2*y*(-1/2 - sqrt(3)*I/2)/3)/(x + 1/2 + sqrt(3)*I/2) + (-y/3 -
    2*y*(-1/2 + sqrt(3)*I/2)/3)/(x + 1/2 - sqrt(3)*I/2)
sympy.polys.partfrac.apart_list(f, x=None, dummies=None, **options)[source]

Compute partial fraction decomposition of a rational function and return the result in structured form.

Given a rational function f compute the partial fraction decomposition of f. Only Bronstein’s full partial fraction decomposition algorithm is supported by this method. The return value is highly structured and perfectly suited for further algorithmic treatment rather than being human-readable. The function returns a tuple holding three elements:

  • The first item is the common coefficient, free of the variable \(x\) used for decomposition. (It is an element of the base field \(K\).)

  • The second item is the polynomial part of the decomposition. This can be the zero polynomial. (It is an element of \(K[x]\).)

  • The third part itself is a list of quadruples. Each quadruple has the following elements in this order:

    • The (not necessarily irreducible) polynomial \(D\) whose roots \(w_i\) appear in the linear denominator of a bunch of related fraction terms. (This item can also be a list of explicit roots. However, at the moment apart_list never returns a result this way, but the related assemble_partfrac_list function accepts this format as input.)

    • The numerator of the fraction, written as a function of the root \(w\)

    • The linear denominator of the fraction excluding its power exponent, written as a function of the root \(w\).

    • The power to which the denominator has to be raised.

On can always rebuild a plain expression by using the function assemble_partfrac_list.

Examples

A first example:

>>> from sympy.polys.partfrac import apart_list, assemble_partfrac_list
>>> from sympy.abc import x, t
>>> f = (2*x**3 - 2*x) / (x**2 - 2*x + 1)
>>> pfd = apart_list(f)
>>> pfd
(1,
Poly(2*x + 4, x, domain='ZZ'),
[(Poly(_w - 1, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1)])
>>> assemble_partfrac_list(pfd)
2*x + 4 + 4/(x - 1)

Second example:

>>> f = (-2*x - 2*x**2) / (3*x**2 - 6*x)
>>> pfd = apart_list(f)
>>> pfd
(-1,
Poly(2/3, x, domain='QQ'),
[(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)])
>>> assemble_partfrac_list(pfd)
-2/3 - 2/(x - 2)

Another example, showing symbolic parameters:

>>> pfd = apart_list(t/(x**2 + x + t), x)
>>> pfd
(1,
Poly(0, x, domain='ZZ[t]'),
[(Poly(_w**2 + _w + t, _w, domain='ZZ[t]'),
Lambda(_a, -2*_a*t/(4*t - 1) - t/(4*t - 1)),
Lambda(_a, -_a + x),
1)])
>>> assemble_partfrac_list(pfd)
RootSum(_w**2 + _w + t, Lambda(_a, (-2*_a*t/(4*t - 1) - t/(4*t - 1))/(-_a + x)))

This example is taken from Bronstein’s original paper:

>>> f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2)
>>> pfd = apart_list(f)
>>> pfd
(1,
Poly(0, x, domain='ZZ'),
[(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1),
(Poly(_w**2 - 1, _w, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2),
(Poly(_w + 1, _w, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)])
>>> assemble_partfrac_list(pfd)
-4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2)

References

sympy.polys.partfrac.assemble_partfrac_list(partial_list)[source]

Reassemble a full partial fraction decomposition from a structured result obtained by the function apart_list.

Examples

This example is taken from Bronstein’s original paper:

>>> from sympy.polys.partfrac import apart_list, assemble_partfrac_list
>>> from sympy.abc import x
>>> f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2)
>>> pfd = apart_list(f)
>>> pfd
(1,
Poly(0, x, domain='ZZ'),
[(Poly(_w - 2, _w, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1),
(Poly(_w**2 - 1, _w, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2),
(Poly(_w + 1, _w, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)])
>>> assemble_partfrac_list(pfd)
-4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2)

If we happen to know some roots we can provide them easily inside the structure:

>>> pfd = apart_list(2/(x**2-2))
>>> pfd
(1,
Poly(0, x, domain='ZZ'),
[(Poly(_w**2 - 2, _w, domain='ZZ'),
Lambda(_a, _a/2),
Lambda(_a, -_a + x),
1)])
>>> pfda = assemble_partfrac_list(pfd)
>>> pfda
RootSum(_w**2 - 2, Lambda(_a, _a/(-_a + x)))/2
>>> pfda.doit()
-sqrt(2)/(2*(x + sqrt(2))) + sqrt(2)/(2*(x - sqrt(2)))
>>> from sympy import Dummy, Poly, Lambda, sqrt
>>> a = Dummy("a")
>>> pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)])
>>> assemble_partfrac_list(pfd)
-sqrt(2)/(2*(x + sqrt(2))) + sqrt(2)/(2*(x - sqrt(2)))

See also

apart, apart_list

Dispersion of Polynomials

sympy.polys.dispersion.dispersionset(p, q=None, *gens, **args)[source]

Compute the dispersion set of two polynomials.

For two polynomials \(f(x)\) and \(g(x)\) with \(\deg f > 0\) and \(\deg g > 0\) the dispersion set \(\operatorname{J}(f, g)\) is defined as:

\[\begin{split}\operatorname{J}(f, g) & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}\end{split}\]

For a single polynomial one defines \(\operatorname{J}(f) := \operatorname{J}(f, f)\).

Examples

>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x

Dispersion set and dispersion of a simple polynomial:

>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6

Note that the definition of the dispersion is not symmetric:

>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo

Computing the dispersion also works over field extensions:

>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]

We can even perform the computations for polynomials having symbolic coefficients:

>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]

See also

dispersion

References

sympy.polys.dispersion.dispersion(p, q=None, *gens, **args)[source]

Compute the dispersion of polynomials.

For two polynomials \(f(x)\) and \(g(x)\) with \(\deg f > 0\) and \(\deg g > 0\) the dispersion \(\operatorname{dis}(f, g)\) is defined as:

\[\begin{split}\operatorname{dis}(f, g) & := \max\{ J(f,g) \cup \{0\} \} \\ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}\end{split}\]

and for a single polynomial \(\operatorname{dis}(f) := \operatorname{dis}(f, f)\). Note that we make the definition \(\max\{\} := -\infty\).

Examples

>>> from sympy import poly
>>> from sympy.polys.dispersion import dispersion, dispersionset
>>> from sympy.abc import x

Dispersion set and dispersion of a simple polynomial:

>>> fp = poly((x - 3)*(x + 3), x)
>>> sorted(dispersionset(fp))
[0, 6]
>>> dispersion(fp)
6

Note that the definition of the dispersion is not symmetric:

>>> fp = poly(x**4 - 3*x**2 + 1, x)
>>> gp = fp.shift(-3)
>>> sorted(dispersionset(fp, gp))
[2, 3, 4]
>>> dispersion(fp, gp)
4
>>> sorted(dispersionset(gp, fp))
[]
>>> dispersion(gp, fp)
-oo

The maximum of an empty set is defined to be \(-\infty\) as seen in this example.

Computing the dispersion also works over field extensions:

>>> from sympy import sqrt
>>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
>>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
>>> sorted(dispersionset(fp, gp))
[2]
>>> sorted(dispersionset(gp, fp))
[1, 4]

We can even perform the computations for polynomials having symbolic coefficients:

>>> from sympy.abc import a
>>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
>>> sorted(dispersionset(fp))
[0, 1]

See also

dispersionset

References