Reference docs for the Poly Domains

This page lists the reference documentation for the domains in the polys module. For a general introduction to the polys module it is recommended to read Basic functionality of the module instead. For an introductory explanation of the what the domain system is and how it is used it is recommended to read Introducing the Domains of the poly module. This page lists the reference docs for the Domain class and its subclasses (the specific domains such as ZZ) as well as the classes that represent the domain elements.

Domains

Here we document the various implemented ground domains (see Introducing the Domains of the poly module for more of an explanation). There are three types of Domain subclass: abstract domains, concrete domains, and “implementation domains”. Abstract domains cannot be (usefully) instantiated at all, and just collect together functionality shared by many other domains. Concrete domains are those meant to be instantiated and used in the polynomial manipulation algorithms. In some cases, there are various possible ways to implement the data type the domain provides. For example, depending on what libraries are available on the system, the integers are implemented either using the python built-in integers, or using gmpy. Note that various aliases are created automatically depending on the libraries available. As such e.g. ZZ always refers to the most efficient implementation of the integer ring available.

Abstract Domains

class sympy.polys.domains.domain.Domain[source]

Superclass for all domains in the polys domains system.

See Introducing the Domains of the poly module for an introductory explanation of the domains system.

The Domain class is an abstract base class for all of the concrete domain types. There are many different Domain subclasses each of which has an associated dtype which is a class representing the elements of the domain. The coefficients of a Poly are elements of a domain which must be a subclass of Domain.

Examples

The most common example domains are the integers ZZ and the rationals QQ.

>>> from sympy import Poly, symbols, Domain
>>> x, y = symbols('x, y')
>>> p = Poly(x**2 + y)
>>> p
Poly(x**2 + y, x, y, domain='ZZ')
>>> p.domain
ZZ
>>> isinstance(p.domain, Domain)
True
>>> Poly(x**2 + y/2)
Poly(x**2 + 1/2*y, x, y, domain='QQ')

The domains can be used directly in which case the domain object e.g. (ZZ or QQ) can be used as a constructor for elements of dtype.

>>> from sympy import ZZ, QQ
>>> ZZ(2)
2
>>> ZZ.dtype  
<class 'int'>
>>> type(ZZ(2))  
<class 'int'>
>>> QQ(1, 2)
1/2
>>> type(QQ(1, 2))  
<class 'sympy.polys.domains.pythonrational.PythonRational'>

The corresponding domain elements can be used with the arithmetic operations +,-,*,** and depending on the domain some combination of /,//,% might be usable. For example in ZZ both // (floor division) and % (modulo division) can be used but / (true division) cannot. Since QQ is a Field its elements can be used with / but // and % should not be used. Some domains have a gcd() method.

>>> ZZ(2) + ZZ(3)
5
>>> ZZ(5) // ZZ(2)
2
>>> ZZ(5) % ZZ(2)
1
>>> QQ(1, 2) / QQ(2, 3)
3/4
>>> ZZ.gcd(ZZ(4), ZZ(2))
2
>>> QQ.gcd(QQ(2,7), QQ(5,3))
1/21
>>> ZZ.is_Field
False
>>> QQ.is_Field
True

There are also many other domains including:

  1. GF(p) for finite fields of prime order.

  2. RR for real (floating point) numbers.

  3. CC for complex (floating point) numbers.

  4. QQ<a> for algebraic number fields.

  5. K[x] for polynomial rings.

  6. K(x) for rational function fields.

  7. EX for arbitrary expressions.

Each domain is represented by a domain object and also an implementation class (dtype) for the elements of the domain. For example the K[x] domains are represented by a domain object which is an instance of PolynomialRing and the elements are always instances of PolyElement. The implementation class represents particular types of mathematical expressions in a way that is more efficient than a normal SymPy expression which is of type Expr. The domain methods from_sympy() and to_sympy() are used to convert from Expr to a domain element and vice versa.

>>> from sympy import Symbol, ZZ, Expr
>>> x = Symbol('x')
>>> K = ZZ[x]           # polynomial ring domain
>>> K
ZZ[x]
>>> type(K)             # class of the domain
<class 'sympy.polys.domains.polynomialring.PolynomialRing'>
>>> K.dtype             # class of the elements
<class 'sympy.polys.rings.PolyElement'>
>>> p_expr = x**2 + 1   # Expr
>>> p_expr
x**2 + 1
>>> type(p_expr)
<class 'sympy.core.add.Add'>
>>> isinstance(p_expr, Expr)
True
>>> p_domain = K.from_sympy(p_expr)
>>> p_domain            # domain element
x**2 + 1
>>> type(p_domain)
<class 'sympy.polys.rings.PolyElement'>
>>> K.to_sympy(p_domain) == p_expr
True

The convert_from() method is used to convert domain elements from one domain to another.

>>> from sympy import ZZ, QQ
>>> ez = ZZ(2)
>>> eq = QQ.convert_from(ez, ZZ)
>>> type(ez)  
<class 'int'>
>>> type(eq)  
<class 'sympy.polys.domains.pythonrational.PythonRational'>

Elements from different domains should not be mixed in arithmetic or other operations: they should be converted to a common domain first. The domain method unify() is used to find a domain that can represent all the elements of two given domains.

>>> from sympy import ZZ, QQ, symbols
>>> x, y = symbols('x, y')
>>> ZZ.unify(QQ)
QQ
>>> ZZ[x].unify(QQ)
QQ[x]
>>> ZZ[x].unify(QQ[y])
QQ[x,y]

If a domain is a Ring then is might have an associated Field and vice versa. The get_field() and get_ring() methods will find or create the associated domain.

>>> from sympy import ZZ, QQ, Symbol
>>> x = Symbol('x')
>>> ZZ.has_assoc_Field
True
>>> ZZ.get_field()
QQ
>>> QQ.has_assoc_Ring
True
>>> QQ.get_ring()
ZZ
>>> K = QQ[x]
>>> K
QQ[x]
>>> K.get_field()
QQ(x)

See also

DomainElement

abstract base class for domain elements

construct_domain

construct a minimal domain for some expressions

abs(a)[source]

Absolute value of a, implies __abs__.

add(a, b)[source]

Sum of a and b, implies __add__.

algebraic_field(*extension)[source]

Returns an algebraic field, i.e. \(K(\alpha, \ldots)\).

almosteq(a, b, tolerance=None)[source]

Check if a and b are almost equal.

characteristic()[source]

Return the characteristic of this domain.

cofactors(a, b)[source]

Returns GCD and cofactors of a and b.

convert(element, base=None)[source]

Convert element to self.dtype.

convert_from(element, base)[source]

Convert element to self.dtype given the base domain.

denom(a)[source]

Returns denominator of a.

div(a, b)[source]

Quotient and remainder for a and b. Analogue of divmod(a, b)

Parameters:

a: domain element

The dividend

b: domain element

The divisor

Returns:

(q, r): tuple of domain elements

The quotient and remainder

Raises:

ZeroDivisionError: when the divisor is zero.

Explanation

This is essentially the same as divmod(a, b) except that is more consistent when working over some Field domains such as QQ. When working over an arbitrary Domain the div() method should be used instead of divmod.

The key invariant is that if q, r = K.div(a, b) then a == b*q + r.

The result of K.div(a, b) is the same as the tuple (K.quo(a, b), K.rem(a, b)) except that if both quotient and remainder are needed then it is more efficient to use div().

Examples

We can use K.div instead of divmod for floor division and remainder.

>>> from sympy import ZZ, QQ
>>> ZZ.div(ZZ(5), ZZ(2))
(2, 1)

If K is a Field then the division is always exact with a remainder of zero.

>>> QQ.div(QQ(5), QQ(2))
(5/2, 0)

Notes

If gmpy is installed then the gmpy.mpq type will be used as the dtype for QQ. The gmpy.mpq type defines divmod in a way that is undesirable so div() should be used instead of divmod.

>>> a = QQ(1)
>>> b = QQ(3, 2)
>>> a               
mpq(1,1)
>>> b               
mpq(3,2)
>>> divmod(a, b)    
(mpz(0), mpq(1,1))
>>> QQ.div(a, b)    
(mpq(2,3), mpq(0,1))

Using // or % with QQ will lead to incorrect results so div() should be used instead.

See also

quo

Analogue of a // b

rem

Analogue of a % b

exquo

Analogue of a / b

drop(*symbols)[source]

Drop generators from this domain.

dtype: Type | None = None

The type (class) of the elements of this Domain:

>>> from sympy import ZZ, QQ, Symbol
>>> ZZ.dtype
<class 'int'>
>>> z = ZZ(2)
>>> z
2
>>> type(z)
<class 'int'>
>>> type(z) == ZZ.dtype
True

Every domain has an associated dtype (“datatype”) which is the class of the associated domain elements.

See also

of_type

evalf(a, prec=None, **options)[source]

Returns numerical approximation of a.

exquo(a, b)[source]

Exact quotient of a and b. Analogue of a / b.

Parameters:

a: domain element

The dividend

b: domain element

The divisor

Returns:

q: domain element

The exact quotient

Raises:

ExactQuotientFailed: if exact division is not possible.

ZeroDivisionError: when the divisor is zero.

Explanation

This is essentially the same as a / b except that an error will be raised if the division is inexact (if there is any remainder) and the result will always be a domain element. When working in a Domain that is not a Field (e.g. ZZ or K[x]) exquo should be used instead of /.

The key invariant is that if q = K.exquo(a, b) (and exquo does not raise an exception) then a == b*q.

Examples

We can use K.exquo instead of / for exact division.

>>> from sympy import ZZ
>>> ZZ.exquo(ZZ(4), ZZ(2))
2
>>> ZZ.exquo(ZZ(5), ZZ(2))
Traceback (most recent call last):
    ...
ExactQuotientFailed: 2 does not divide 5 in ZZ

Over a Field such as QQ, division (with nonzero divisor) is always exact so in that case / can be used instead of exquo().

>>> from sympy import QQ
>>> QQ.exquo(QQ(5), QQ(2))
5/2
>>> QQ(5) / QQ(2)
5/2

Notes

Since the default dtype for ZZ is int (or mpz) division as a / b should not be used as it would give a float.

>>> ZZ(4) / ZZ(2)
2.0
>>> ZZ(5) / ZZ(2)
2.5

Using / with ZZ will lead to incorrect results so exquo() should be used instead.

See also

quo

Analogue of a // b

rem

Analogue of a % b

div

Analogue of divmod(a, b)

frac_field(*symbols, order=LexOrder())[source]

Returns a fraction field, i.e. \(K(X)\).

from_AlgebraicField(a, K0)[source]

Convert an algebraic number to dtype.

from_ComplexField(a, K0)[source]

Convert a complex element to dtype.

from_ExpressionDomain(a, K0)[source]

Convert a EX object to dtype.

from_ExpressionRawDomain(a, K0)[source]

Convert a EX object to dtype.

from_FF(a, K0)[source]

Convert ModularInteger(int) to dtype.

from_FF_gmpy(a, K0)[source]

Convert ModularInteger(mpz) to dtype.

from_FF_python(a, K0)[source]

Convert ModularInteger(int) to dtype.

from_FractionField(a, K0)[source]

Convert a rational function to dtype.

from_GlobalPolynomialRing(a, K0)[source]

Convert a polynomial to dtype.

from_MonogenicFiniteExtension(a, K0)[source]

Convert an ExtensionElement to dtype.

from_PolynomialRing(a, K0)[source]

Convert a polynomial to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a real element object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert a SymPy expression to an element of this domain.

Parameters:

expr: Expr

A normal SymPy expression of type Expr.

Returns:

a: domain element

An element of this Domain.

Explanation

See to_sympy() for explanation and examples.

gcd(a, b)[source]

Returns GCD of a and b.

gcdex(a, b)[source]

Extended GCD of a and b.

get_exact()[source]

Returns an exact domain associated with self.

get_field()[source]

Returns a field associated with self.

get_ring()[source]

Returns a ring associated with self.

half_gcdex(a, b)[source]

Half extended GCD of a and b.

has_assoc_Field = False

Boolean flag indicating if the domain has an associated Field.

>>> from sympy import ZZ
>>> ZZ.has_assoc_Field
True
>>> ZZ.get_field()
QQ

See also

is_Field, get_field

has_assoc_Ring = False

Boolean flag indicating if the domain has an associated Ring.

>>> from sympy import QQ
>>> QQ.has_assoc_Ring
True
>>> QQ.get_ring()
ZZ

See also

is_Field, get_ring

inject(*symbols)[source]

Inject generators into this domain.

invert(a, b)[source]

Returns inversion of a mod b, implies something.

is_Field = False

Boolean flag indicating if the domain is a Field.

>>> from sympy import ZZ, QQ
>>> ZZ.is_Field
False
>>> QQ.is_Field
True
is_PID = False

Boolean flag indicating if the domain is a principal ideal domain.

>>> from sympy import ZZ
>>> ZZ.has_assoc_Field
True
>>> ZZ.get_field()
QQ

See also

is_Field, get_field

is_Ring = False

Boolean flag indicating if the domain is a Ring.

>>> from sympy import ZZ
>>> ZZ.is_Ring
True

Basically every Domain represents a ring so this flag is not that useful.

is_negative(a)[source]

Returns True if a is negative.

is_nonnegative(a)[source]

Returns True if a is non-negative.

is_nonpositive(a)[source]

Returns True if a is non-positive.

is_one(a)[source]

Returns True if a is one.

is_positive(a)[source]

Returns True if a is positive.

is_zero(a)[source]

Returns True if a is zero.

lcm(a, b)[source]

Returns LCM of a and b.

log(a, b)[source]

Returns b-base logarithm of a.

map(seq)[source]

Rersively apply self to all elements of seq.

mul(a, b)[source]

Product of a and b, implies __mul__.

n(a, prec=None, **options)[source]

Returns numerical approximation of a.

neg(a)[source]

Returns a negated, implies __neg__.

numer(a)[source]

Returns numerator of a.

of_type(element)[source]

Check if a is of type dtype.

old_frac_field(*symbols, **kwargs)[source]

Returns a fraction field, i.e. \(K(X)\).

old_poly_ring(*symbols, **kwargs)[source]

Returns a polynomial ring, i.e. \(K[X]\).

one: Any | None = None

The one element of the Domain:

>>> from sympy import QQ
>>> QQ.one
1
>>> QQ.of_type(QQ.one)
True

See also

of_type, zero

poly_ring(*symbols, order=LexOrder())[source]

Returns a polynomial ring, i.e. \(K[X]\).

pos(a)[source]

Returns a positive, implies __pos__.

pow(a, b)[source]

Raise a to power b, implies __pow__.

quo(a, b)[source]

Quotient of a and b. Analogue of a // b.

K.quo(a, b) is equivalent to K.div(a, b)[0]. See div() for more explanation.

See also

rem

Analogue of a % b

div

Analogue of divmod(a, b)

exquo

Analogue of a / b

rem(a, b)[source]

Modulo division of a and b. Analogue of a % b.

K.rem(a, b) is equivalent to K.div(a, b)[1]. See div() for more explanation.

See also

quo

Analogue of a // b

div

Analogue of divmod(a, b)

exquo

Analogue of a / b

revert(a)[source]

Returns a**(-1) if possible.

sqrt(a)[source]

Returns square root of a.

sub(a, b)[source]

Difference of a and b, implies __sub__.

to_sympy(a)[source]

Convert domain element a to a SymPy expression (Expr).

Parameters:

a: domain element

An element of this Domain.

Returns:

expr: Expr

A normal SymPy expression of type Expr.

Explanation

Convert a Domain element a to Expr. Most public SymPy functions work with objects of type Expr. The elements of a Domain have a different internal representation. It is not possible to mix domain elements with Expr so each domain has to_sympy() and from_sympy() methods to convert its domain elements to and from Expr.

Examples

Construct an element of the QQ domain and then convert it to Expr.

>>> from sympy import QQ, Expr
>>> q_domain = QQ(2)
>>> q_domain
2
>>> q_expr = QQ.to_sympy(q_domain)
>>> q_expr
2

Although the printed forms look similar these objects are not of the same type.

>>> isinstance(q_domain, Expr)
False
>>> isinstance(q_expr, Expr)
True

Construct an element of K[x] and convert to Expr.

>>> from sympy import Symbol
>>> x = Symbol('x')
>>> K = QQ[x]
>>> x_domain = K.gens[0]  # generator x as a domain element
>>> p_domain = x_domain**2/3 + 1
>>> p_domain
1/3*x**2 + 1
>>> p_expr = K.to_sympy(p_domain)
>>> p_expr
x**2/3 + 1

The from_sympy() method is used for the opposite conversion from a normal SymPy expression to a domain element.

>>> p_domain == p_expr
False
>>> K.from_sympy(p_expr) == p_domain
True
>>> K.to_sympy(p_domain) == p_expr
True
>>> K.from_sympy(K.to_sympy(p_domain)) == p_domain
True
>>> K.to_sympy(K.from_sympy(p_expr)) == p_expr
True

The from_sympy() method makes it easier to construct domain elements interactively.

>>> from sympy import Symbol
>>> x = Symbol('x')
>>> K = QQ[x]
>>> K.from_sympy(x**2/3 + 1)
1/3*x**2 + 1
property tp

Alias for dtype

unify(K1, symbols=None)[source]

Construct a minimal domain that contains elements of K0 and K1.

Known domains (from smallest to largest):

  • GF(p)

  • ZZ

  • QQ

  • RR(prec, tol)

  • CC(prec, tol)

  • ALG(a, b, c)

  • K[x, y, z]

  • K(x, y, z)

  • EX

zero: Any | None = None

The zero element of the Domain:

>>> from sympy import QQ
>>> QQ.zero
0
>>> QQ.of_type(QQ.zero)
True

See also

of_type, one

class sympy.polys.domains.domainelement.DomainElement[source]

Represents an element of a domain.

Mix in this trait into a class whose instances should be recognized as elements of a domain. Method parent() gives that domain.

parent()[source]

Get the domain associated with self

Examples

>>> from sympy import ZZ, symbols
>>> x, y = symbols('x, y')
>>> K = ZZ[x,y]
>>> p = K(x)**2 + K(y)**2
>>> p
x**2 + y**2
>>> p.parent()
ZZ[x,y]

Notes

This is used by convert() to identify the domain associated with a domain element.

class sympy.polys.domains.field.Field[source]

Represents a field domain.

div(a, b)[source]

Division of a and b, implies __truediv__.

exquo(a, b)[source]

Exact quotient of a and b, implies __truediv__.

gcd(a, b)[source]

Returns GCD of a and b.

This definition of GCD over fields allows to clear denominators in \(primitive()\).

Examples

>>> from sympy.polys.domains import QQ
>>> from sympy import S, gcd, primitive
>>> from sympy.abc import x
>>> QQ.gcd(QQ(2, 3), QQ(4, 9))
2/9
>>> gcd(S(2)/3, S(4)/9)
2/9
>>> primitive(2*x/3 + S(4)/9)
(2/9, 3*x + 2)
get_field()[source]

Returns a field associated with self.

get_ring()[source]

Returns a ring associated with self.

is_unit(a)[source]

Return true if a is a invertible

lcm(a, b)[source]

Returns LCM of a and b.

>>> from sympy.polys.domains import QQ
>>> from sympy import S, lcm
>>> QQ.lcm(QQ(2, 3), QQ(4, 9))
4/3
>>> lcm(S(2)/3, S(4)/9)
4/3
quo(a, b)[source]

Quotient of a and b, implies __truediv__.

rem(a, b)[source]

Remainder of a and b, implies nothing.

revert(a)[source]

Returns a**(-1) if possible.

class sympy.polys.domains.ring.Ring[source]

Represents a ring domain.

denom(a)[source]

Returns denominator of \(a\).

div(a, b)[source]

Division of a and b, implies __divmod__.

exquo(a, b)[source]

Exact quotient of a and b, implies __floordiv__.

free_module(rank)[source]

Generate a free module of rank rank over self.

>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
get_ring()[source]

Returns a ring associated with self.

ideal(*gens)[source]

Generate an ideal of self.

>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).ideal(x**2)
<x**2>
invert(a, b)[source]

Returns inversion of a mod b.

numer(a)[source]

Returns numerator of a.

quo(a, b)[source]

Quotient of a and b, implies __floordiv__.

quotient_ring(e)[source]

Form a quotient ring of self.

Here e can be an ideal or an iterable.

>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2))
QQ[x]/<x**2>
>>> QQ.old_poly_ring(x).quotient_ring([x**2])
QQ[x]/<x**2>

The division operator has been overloaded for this:

>>> QQ.old_poly_ring(x)/[x**2]
QQ[x]/<x**2>
rem(a, b)[source]

Remainder of a and b, implies __mod__.

revert(a)[source]

Returns a**(-1) if possible.

class sympy.polys.domains.simpledomain.SimpleDomain[source]

Base class for simple domains, e.g. ZZ, QQ.

inject(*gens)[source]

Inject generators into this domain.

class sympy.polys.domains.compositedomain.CompositeDomain[source]

Base class for composite domains, e.g. ZZ[x], ZZ(X).

drop(*symbols)[source]

Drop generators from this domain.

inject(*symbols)[source]

Inject generators into this domain.

GF(p)

class sympy.polys.domains.FiniteField(mod, symmetric=True)[source]

Finite field of prime order GF(p)

A GF(p) domain represents a finite field \(\mathbb{F}_p\) of prime order as Domain in the domain system (see Introducing the Domains of the poly module).

A Poly created from an expression with integer coefficients will have the domain ZZ. However, if the modulus=p option is given then the domain will be a finite field instead.

>>> from sympy import Poly, Symbol
>>> x = Symbol('x')
>>> p = Poly(x**2 + 1)
>>> p
Poly(x**2 + 1, x, domain='ZZ')
>>> p.domain
ZZ
>>> p2 = Poly(x**2 + 1, modulus=2)
>>> p2
Poly(x**2 + 1, x, modulus=2)
>>> p2.domain
GF(2)

It is possible to factorise a polynomial over GF(p) using the modulus argument to factor() or by specifying the domain explicitly. The domain can also be given as a string.

>>> from sympy import factor, GF
>>> factor(x**2 + 1)
x**2 + 1
>>> factor(x**2 + 1, modulus=2)
(x + 1)**2
>>> factor(x**2 + 1, domain=GF(2))
(x + 1)**2
>>> factor(x**2 + 1, domain='GF(2)')
(x + 1)**2

It is also possible to use GF(p) with the cancel() and gcd() functions.

>>> from sympy import cancel, gcd
>>> cancel((x**2 + 1)/(x + 1))
(x**2 + 1)/(x + 1)
>>> cancel((x**2 + 1)/(x + 1), domain=GF(2))
x + 1
>>> gcd(x**2 + 1, x + 1)
1
>>> gcd(x**2 + 1, x + 1, domain=GF(2))
x + 1

When using the domain directly GF(p) can be used as a constructor to create instances which then support the operations +,-,*,**,/

>>> from sympy import GF
>>> K = GF(5)
>>> K
GF(5)
>>> x = K(3)
>>> y = K(2)
>>> x
3 mod 5
>>> y
2 mod 5
>>> x * y
1 mod 5
>>> x / y
4 mod 5

Notes

It is also possible to create a GF(p) domain of non-prime order but the resulting ring is not a field: it is just the ring of the integers modulo n.

>>> K = GF(9)
>>> z = K(3)
>>> z
3 mod 9
>>> z**2
0 mod 9

It would be good to have a proper implementation of prime power fields (GF(p**n)) but these are not yet implemented in SymPY.

characteristic()[source]

Return the characteristic of this domain.

from_FF(a, K0=None)[source]

Convert ModularInteger(int) to dtype.

from_FF_gmpy(a, K0=None)[source]

Convert ModularInteger(mpz) to dtype.

from_FF_python(a, K0=None)[source]

Convert ModularInteger(int) to dtype.

from_QQ(a, K0=None)[source]

Convert Python’s Fraction to dtype.

from_QQ_gmpy(a, K0=None)[source]

Convert GMPY’s mpq to dtype.

from_QQ_python(a, K0=None)[source]

Convert Python’s Fraction to dtype.

from_RealField(a, K0)[source]

Convert mpmath’s mpf to dtype.

from_ZZ(a, K0=None)[source]

Convert Python’s int to dtype.

from_ZZ_gmpy(a, K0=None)[source]

Convert GMPY’s mpz to dtype.

from_ZZ_python(a, K0=None)[source]

Convert Python’s int to dtype.

from_sympy(a)[source]

Convert SymPy’s Integer to SymPy’s Integer.

get_field()[source]

Returns a field associated with self.

to_sympy(a)[source]

Convert a to a SymPy object.

class sympy.polys.domains.PythonFiniteField(mod, symmetric=True)[source]

Finite field based on Python’s integers.

class sympy.polys.domains.GMPYFiniteField(mod, symmetric=True)[source]

Finite field based on GMPY integers.

ZZ

The ZZ domain represents the integers \(\mathbb{Z}\) as a Domain in the domain system (see Introducing the Domains of the poly module).

By default a Poly created from an expression with integer coefficients will have the domain ZZ:

>>> from sympy import Poly, Symbol
>>> x = Symbol('x')
>>> p = Poly(x**2 + 1)
>>> p
Poly(x**2 + 1, x, domain='ZZ')
>>> p.domain
ZZ

The corresponding field of fractions is the domain of the rationals QQ. Conversely ZZ is the ring of integers of QQ:

>>> from sympy import ZZ, QQ
>>> ZZ.get_field()
QQ
>>> QQ.get_ring()
ZZ

When using the domain directly ZZ can be used as a constructor to create instances which then support the operations +,-,*,**,//,% (true division / should not be used with ZZ - see the exquo() domain method):

>>> x = ZZ(5)
>>> y = ZZ(2)
>>> x // y  # floor division
2
>>> x % y   # modulo division (remainder)
1

The gcd() method can be used to compute the gcd of any two elements:

>>> ZZ.gcd(ZZ(10), ZZ(2))
2

There are two implementations of ZZ in SymPy. If gmpy or gmpy2 is installed then ZZ will be implemented by GMPYIntegerRing and the elements will be instances of the gmpy.mpz type. Otherwise if gmpy and gmpy2 are not installed then ZZ will be implemented by PythonIntegerRing which uses Python’s standard builtin int type. With larger integers gmpy can be more efficient so it is preferred when available.

class sympy.polys.domains.IntegerRing[source]

The domain ZZ representing the integers \(\mathbb{Z}\).

The IntegerRing class represents the ring of integers as a Domain in the domain system. IntegerRing is a super class of PythonIntegerRing and GMPYIntegerRing one of which will be the implementation for ZZ depending on whether or not gmpy or gmpy2 is installed.

See also

Domain

algebraic_field(*extension)[source]

Returns an algebraic field, i.e. \(\mathbb{Q}(\alpha, \ldots)\).

Parameters:

*extension: One or more Expr.

Generators of the extension. These should be expressions that are algebraic over \(\mathbb{Q}\).

Returns:

AlgebraicField

A Domain representing the algebraic field extension.

Examples

>>> from sympy import ZZ, sqrt
>>> ZZ.algebraic_field(sqrt(2))
QQ<sqrt(2)>
factorial(a)[source]

Compute factorial of a.

from_AlgebraicField(a, K0)[source]

Convert a ANP object to ZZ.

See convert().

from_FF(a, K0)[source]

Convert ModularInteger(int) to GMPY’s mpz.

from_FF_gmpy(a, K0)[source]

Convert ModularInteger(mpz) to GMPY’s mpz.

from_FF_python(a, K0)[source]

Convert ModularInteger(int) to GMPY’s mpz.

from_QQ(a, K0)[source]

Convert Python’s Fraction to GMPY’s mpz.

from_QQ_gmpy(a, K0)[source]

Convert GMPY mpq to GMPY’s mpz.

from_QQ_python(a, K0)[source]

Convert Python’s Fraction to GMPY’s mpz.

from_RealField(a, K0)[source]

Convert mpmath’s mpf to GMPY’s mpz.

from_ZZ(a, K0)[source]

Convert Python’s int to GMPY’s mpz.

from_ZZ_gmpy(a, K0)[source]

Convert GMPY’s mpz to GMPY’s mpz.

from_ZZ_python(a, K0)[source]

Convert Python’s int to GMPY’s mpz.

from_sympy(a)[source]

Convert SymPy’s Integer to dtype.

gcd(a, b)[source]

Compute GCD of a and b.

gcdex(a, b)[source]

Compute extended GCD of a and b.

get_field()[source]

Return the associated field of fractions QQ

Returns:

QQ:

The associated field of fractions QQ, a Domain representing the rational numbers \(\mathbb{Q}\).

Examples

>>> from sympy import ZZ
>>> ZZ.get_field()
QQ
lcm(a, b)[source]

Compute LCM of a and b.

log(a, b)[source]

logarithm of a to the base b

Parameters:

a: number

b: number

Returns:

\(\\lfloor\log(a, b)\\rfloor\):

Floor of the logarithm of a to the base b

Examples

>>> from sympy import ZZ
>>> ZZ.log(ZZ(8), ZZ(2))
3
>>> ZZ.log(ZZ(9), ZZ(2))
3

Notes

This function uses math.log which is based on float so it will fail for large integer arguments.

sqrt(a)[source]

Compute square root of a.

to_sympy(a)[source]

Convert a to a SymPy object.

class sympy.polys.domains.PythonIntegerRing[source]

Integer ring based on Python’s int type.

This will be used as ZZ if gmpy and gmpy2 are not installed. Elements are instances of the standard Python int type.

class sympy.polys.domains.GMPYIntegerRing[source]

Integer ring based on GMPY’s mpz type.

This will be the implementation of ZZ if gmpy or gmpy2 is installed. Elements will be of type gmpy.mpz.

factorial(a)[source]

Compute factorial of a.

from_FF_gmpy(a, K0)[source]

Convert ModularInteger(mpz) to GMPY’s mpz.

from_FF_python(a, K0)[source]

Convert ModularInteger(int) to GMPY’s mpz.

from_QQ(a, K0)[source]

Convert Python’s Fraction to GMPY’s mpz.

from_QQ_gmpy(a, K0)[source]

Convert GMPY mpq to GMPY’s mpz.

from_QQ_python(a, K0)[source]

Convert Python’s Fraction to GMPY’s mpz.

from_RealField(a, K0)[source]

Convert mpmath’s mpf to GMPY’s mpz.

from_ZZ_gmpy(a, K0)[source]

Convert GMPY’s mpz to GMPY’s mpz.

from_ZZ_python(a, K0)[source]

Convert Python’s int to GMPY’s mpz.

from_sympy(a)[source]

Convert SymPy’s Integer to dtype.

gcd(a, b)[source]

Compute GCD of a and b.

gcdex(a, b)[source]

Compute extended GCD of a and b.

lcm(a, b)[source]

Compute LCM of a and b.

sqrt(a)[source]

Compute square root of a.

to_sympy(a)[source]

Convert a to a SymPy object.

QQ

The QQ domain represents the rationals \(\mathbb{Q}\) as a Domain in the domain system (see Introducing the Domains of the poly module).

By default a Poly created from an expression with rational coefficients will have the domain QQ:

>>> from sympy import Poly, Symbol
>>> x = Symbol('x')
>>> p = Poly(x**2 + x/2)
>>> p
Poly(x**2 + 1/2*x, x, domain='QQ')
>>> p.domain
QQ

The corresponding ring of integers is the Domain of the integers ZZ. Conversely QQ is the field of fractions of ZZ:

>>> from sympy import ZZ, QQ
>>> QQ.get_ring()
ZZ
>>> ZZ.get_field()
QQ

When using the domain directly QQ can be used as a constructor to create instances which then support the operations +,-,*,**,/ (true division / is always possible for nonzero divisors in QQ):

>>> x = QQ(5)
>>> y = QQ(2)
>>> x / y  # true division
5/2

There are two implementations of QQ in SymPy. If gmpy or gmpy2 is installed then QQ will be implemented by GMPYRationalField and the elements will be instances of the gmpy.mpq type. Otherwise if gmpy and gmpy2 are not installed then QQ will be implemented by PythonRationalField which is a pure Python class as part of sympy. The gmpy implementation is preferred because it is significantly faster.

class sympy.polys.domains.RationalField[source]

Abstract base class for the domain QQ.

The RationalField class represents the field of rational numbers \(\mathbb{Q}\) as a Domain in the domain system. RationalField is a superclass of PythonRationalField and GMPYRationalField one of which will be the implementation for QQ depending on whether either of gmpy or gmpy2 is installed or not.

See also

Domain

algebraic_field(*extension)[source]

Returns an algebraic field, i.e. \(\mathbb{Q}(\alpha, \ldots)\).

Parameters:

*extension: One or more Expr

Generators of the extension. These should be expressions that are algebraic over \(\mathbb{Q}\).

Returns:

AlgebraicField

A Domain representing the algebraic field extension.

Examples

>>> from sympy import QQ, sqrt
>>> QQ.algebraic_field(sqrt(2))
QQ<sqrt(2)>
denom(a)[source]

Returns denominator of a.

div(a, b)[source]

Division of a and b, implies __truediv__.

exquo(a, b)[source]

Exact quotient of a and b, implies __truediv__.

from_AlgebraicField(a, K0)[source]

Convert a ANP object to QQ.

See convert()

from_GaussianRationalField(a, K0)[source]

Convert a GaussianElement object to dtype.

from_QQ(a, K0)[source]

Convert a Python Fraction object to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_ZZ(a, K0)[source]

Convert a Python int object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert SymPy’s Integer to dtype.

get_ring()[source]

Returns ring associated with self.

numer(a)[source]

Returns numerator of a.

quo(a, b)[source]

Quotient of a and b, implies __truediv__.

rem(a, b)[source]

Remainder of a and b, implies nothing.

to_sympy(a)[source]

Convert a to a SymPy object.

class sympy.polys.domains.PythonRationalField[source]

Rational field based on MPQ.

This will be used as QQ if gmpy and gmpy2 are not installed. Elements are instances of MPQ.

class sympy.polys.domains.GMPYRationalField[source]

Rational field based on GMPY’s mpq type.

This will be the implementation of QQ if gmpy or gmpy2 is installed. Elements will be of type gmpy.mpq.

denom(a)[source]

Returns denominator of a.

div(a, b)[source]

Division of a and b, implies __truediv__.

exquo(a, b)[source]

Exact quotient of a and b, implies __truediv__.

factorial(a)[source]

Returns factorial of a.

from_GaussianRationalField(a, K0)[source]

Convert a GaussianElement object to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert SymPy’s Integer to dtype.

get_ring()[source]

Returns ring associated with self.

numer(a)[source]

Returns numerator of a.

quo(a, b)[source]

Quotient of a and b, implies __truediv__.

rem(a, b)[source]

Remainder of a and b, implies nothing.

to_sympy(a)[source]

Convert a to a SymPy object.

class sympy.external.pythonmpq.PythonMPQ(numerator, denominator=None)[source]

Rational number implementation that is intended to be compatible with gmpy2’s mpq.

Also slightly faster than fractions.Fraction.

PythonMPQ should be treated as immutable although no effort is made to prevent mutation (since that might slow down calculations).

MPQ

The MPQ type is either PythonMPQ or otherwise the mpq type from gmpy2.

Gaussian domains

The Gaussian domains ZZ_I and QQ_I share common superclasses GaussianElement for the domain elements and GaussianDomain for the domains themselves.

class sympy.polys.domains.gaussiandomains.GaussianDomain[source]

Base class for Gaussian domains.

from_AlgebraicField(a, K0)[source]

Convert an element from ZZ<I> or QQ<I> to self.dtype.

from_QQ(a, K0)[source]

Convert a GMPY mpq to self.dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq to self.dtype.

from_QQ_python(a, K0)[source]

Convert a QQ_python element to self.dtype.

from_ZZ(a, K0)[source]

Convert a ZZ_python element to self.dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz to self.dtype.

from_ZZ_python(a, K0)[source]

Convert a ZZ_python element to self.dtype.

from_sympy(a)[source]

Convert a SymPy object to self.dtype.

inject(*gens)[source]

Inject generators into this domain.

is_negative(element)[source]

Returns False for any GaussianElement.

is_nonnegative(element)[source]

Returns False for any GaussianElement.

is_nonpositive(element)[source]

Returns False for any GaussianElement.

is_positive(element)[source]

Returns False for any GaussianElement.

to_sympy(a)[source]

Convert a to a SymPy object.

class sympy.polys.domains.gaussiandomains.GaussianElement(x, y=0)[source]

Base class for elements of Gaussian type domains.

classmethod new(x, y)[source]

Create a new GaussianElement of the same domain.

parent()[source]

The domain that this is an element of (ZZ_I or QQ_I)

quadrant()[source]

Return quadrant index 0-3.

0 is included in quadrant 0.

ZZ_I

class sympy.polys.domains.gaussiandomains.GaussianIntegerRing[source]

Ring of Gaussian integers ZZ_I

The ZZ_I domain represents the Gaussian integers \(\mathbb{Z}[i]\) as a Domain in the domain system (see Introducing the Domains of the poly module).

By default a Poly created from an expression with coefficients that are combinations of integers and I (\(\sqrt{-1}\)) will have the domain ZZ_I.

>>> from sympy import Poly, Symbol, I
>>> x = Symbol('x')
>>> p = Poly(x**2 + I)
>>> p
Poly(x**2 + I, x, domain='ZZ_I')
>>> p.domain
ZZ_I

The ZZ_I domain can be used to factorise polynomials that are reducible over the Gaussian integers.

>>> from sympy import factor
>>> factor(x**2 + 1)
x**2 + 1
>>> factor(x**2 + 1, domain='ZZ_I')
(x - I)*(x + I)

The corresponding field of fractions is the domain of the Gaussian rationals QQ_I. Conversely ZZ_I is the ring of integers of QQ_I.

>>> from sympy import ZZ_I, QQ_I
>>> ZZ_I.get_field()
QQ_I
>>> QQ_I.get_ring()
ZZ_I

When using the domain directly ZZ_I can be used as a constructor.

>>> ZZ_I(3, 4)
(3 + 4*I)
>>> ZZ_I(5)
(5 + 0*I)

The domain elements of ZZ_I are instances of GaussianInteger which support the rings operations +,-,*,**.

>>> z1 = ZZ_I(5, 1)
>>> z2 = ZZ_I(2, 3)
>>> z1
(5 + 1*I)
>>> z2
(2 + 3*I)
>>> z1 + z2
(7 + 4*I)
>>> z1 * z2
(7 + 17*I)
>>> z1 ** 2
(24 + 10*I)

Both floor (//) and modulo (%) division work with GaussianInteger (see the div() method).

>>> z3, z4 = ZZ_I(5), ZZ_I(1, 3)
>>> z3 // z4  # floor division
(1 + -1*I)
>>> z3 % z4   # modulo division (remainder)
(1 + -2*I)
>>> (z3//z4)*z4 + z3%z4 == z3
True

True division (/) in ZZ_I gives an element of QQ_I. The exquo() method can be used to divide in ZZ_I when exact division is possible.

>>> z1 / z2
(1 + -1*I)
>>> ZZ_I.exquo(z1, z2)
(1 + -1*I)
>>> z3 / z4
(1/2 + -3/2*I)
>>> ZZ_I.exquo(z3, z4)
Traceback (most recent call last):
    ...
ExactQuotientFailed: (1 + 3*I) does not divide (5 + 0*I) in ZZ_I

The gcd() method can be used to compute the gcd of any two elements.

>>> ZZ_I.gcd(ZZ_I(10), ZZ_I(2))
(2 + 0*I)
>>> ZZ_I.gcd(ZZ_I(5), ZZ_I(2, 1))
(2 + 1*I)
dtype[source]

alias of GaussianInteger

from_GaussianIntegerRing(a, K0)[source]

Convert a ZZ_I element to ZZ_I.

from_GaussianRationalField(a, K0)[source]

Convert a QQ_I element to ZZ_I.

gcd(a, b)[source]

Greatest common divisor of a and b over ZZ_I.

get_field()[source]

Returns a field associated with self.

get_ring()[source]

Returns a ring associated with self.

lcm(a, b)[source]

Least common multiple of a and b over ZZ_I.

normalize(d, *args)[source]

Return first quadrant element associated with d.

Also multiply the other arguments by the same power of i.

class sympy.polys.domains.gaussiandomains.GaussianInteger(x, y=0)[source]

Gaussian integer: domain element for ZZ_I

>>> from sympy import ZZ_I
>>> z = ZZ_I(2, 3)
>>> z
(2 + 3*I)
>>> type(z)
<class 'sympy.polys.domains.gaussiandomains.GaussianInteger'>

QQ_I

class sympy.polys.domains.gaussiandomains.GaussianRationalField[source]

Field of Gaussian rationals QQ_I

The QQ_I domain represents the Gaussian rationals \(\mathbb{Q}(i)\) as a Domain in the domain system (see Introducing the Domains of the poly module).

By default a Poly created from an expression with coefficients that are combinations of rationals and I (\(\sqrt{-1}\)) will have the domain QQ_I.

>>> from sympy import Poly, Symbol, I
>>> x = Symbol('x')
>>> p = Poly(x**2 + I/2)
>>> p
Poly(x**2 + I/2, x, domain='QQ_I')
>>> p.domain
QQ_I

The polys option gaussian=True can be used to specify that the domain should be QQ_I even if the coefficients do not contain I or are all integers.

>>> Poly(x**2)
Poly(x**2, x, domain='ZZ')
>>> Poly(x**2 + I)
Poly(x**2 + I, x, domain='ZZ_I')
>>> Poly(x**2/2)
Poly(1/2*x**2, x, domain='QQ')
>>> Poly(x**2, gaussian=True)
Poly(x**2, x, domain='QQ_I')
>>> Poly(x**2 + I, gaussian=True)
Poly(x**2 + I, x, domain='QQ_I')
>>> Poly(x**2/2, gaussian=True)
Poly(1/2*x**2, x, domain='QQ_I')

The QQ_I domain can be used to factorise polynomials that are reducible over the Gaussian rationals.

>>> from sympy import factor, QQ_I
>>> factor(x**2/4 + 1)
(x**2 + 4)/4
>>> factor(x**2/4 + 1, domain='QQ_I')
(x - 2*I)*(x + 2*I)/4
>>> factor(x**2/4 + 1, domain=QQ_I)
(x - 2*I)*(x + 2*I)/4

It is also possible to specify the QQ_I domain explicitly with polys functions like apart().

>>> from sympy import apart
>>> apart(1/(1 + x**2))
1/(x**2 + 1)
>>> apart(1/(1 + x**2), domain=QQ_I)
I/(2*(x + I)) - I/(2*(x - I))

The corresponding ring of integers is the domain of the Gaussian integers ZZ_I. Conversely QQ_I is the field of fractions of ZZ_I.

>>> from sympy import ZZ_I, QQ_I, QQ
>>> ZZ_I.get_field()
QQ_I
>>> QQ_I.get_ring()
ZZ_I

When using the domain directly QQ_I can be used as a constructor.

>>> QQ_I(3, 4)
(3 + 4*I)
>>> QQ_I(5)
(5 + 0*I)
>>> QQ_I(QQ(2, 3), QQ(4, 5))
(2/3 + 4/5*I)

The domain elements of QQ_I are instances of GaussianRational which support the field operations +,-,*,**,/.

>>> z1 = QQ_I(5, 1)
>>> z2 = QQ_I(2, QQ(1, 2))
>>> z1
(5 + 1*I)
>>> z2
(2 + 1/2*I)
>>> z1 + z2
(7 + 3/2*I)
>>> z1 * z2
(19/2 + 9/2*I)
>>> z2 ** 2
(15/4 + 2*I)

True division (/) in QQ_I gives an element of QQ_I and is always exact.

>>> z1 / z2
(42/17 + -2/17*I)
>>> QQ_I.exquo(z1, z2)
(42/17 + -2/17*I)
>>> z1 == (z1/z2)*z2
True

Both floor (//) and modulo (%) division can be used with GaussianRational (see div()) but division is always exact so there is no remainder.

>>> z1 // z2
(42/17 + -2/17*I)
>>> z1 % z2
(0 + 0*I)
>>> QQ_I.div(z1, z2)
((42/17 + -2/17*I), (0 + 0*I))
>>> (z1//z2)*z2 + z1%z2 == z1
True
as_AlgebraicField()[source]

Get equivalent domain as an AlgebraicField.

denom(a)[source]

Get the denominator of a.

dtype[source]

alias of GaussianRational

from_GaussianIntegerRing(a, K0)[source]

Convert a ZZ_I element to QQ_I.

from_GaussianRationalField(a, K0)[source]

Convert a QQ_I element to QQ_I.

get_field()[source]

Returns a field associated with self.

get_ring()[source]

Returns a ring associated with self.

numer(a)[source]

Get the numerator of a.

class sympy.polys.domains.gaussiandomains.GaussianRational(x, y=0)[source]

Gaussian rational: domain element for QQ_I

>>> from sympy import QQ_I, QQ
>>> z = QQ_I(QQ(2, 3), QQ(4, 5))
>>> z
(2/3 + 4/5*I)
>>> type(z)
<class 'sympy.polys.domains.gaussiandomains.GaussianRational'>

QQ<a>

class sympy.polys.domains.AlgebraicField(dom, *ext)[source]

Algebraic number field QQ<a>

A QQ<a> domain represents an algebraic number field \(\mathbb{Q}(a)\) as a Domain in the domain system (see Introducing the Domains of the poly module).

A Poly created from an expression involving algebraic numbers will treat the algebraic numbers as generators if the generators argument is not specified.

>>> from sympy import Poly, Symbol, sqrt
>>> x = Symbol('x')
>>> Poly(x**2 + sqrt(2))
Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ')

That is a multivariate polynomial with sqrt(2) treated as one of the generators (variables). If the generators are explicitly specified then sqrt(2) will be considered to be a coefficient but by default the EX domain is used. To make a Poly with a QQ<a> domain the argument extension=True can be given.

>>> Poly(x**2 + sqrt(2), x)
Poly(x**2 + sqrt(2), x, domain='EX')
>>> Poly(x**2 + sqrt(2), x, extension=True)
Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>')

A generator of the algebraic field extension can also be specified explicitly which is particularly useful if the coefficients are all rational but an extension field is needed (e.g. to factor the polynomial).

>>> Poly(x**2 + 1)
Poly(x**2 + 1, x, domain='ZZ')
>>> Poly(x**2 + 1, extension=sqrt(2))
Poly(x**2 + 1, x, domain='QQ<sqrt(2)>')

It is possible to factorise a polynomial over a QQ<a> domain using the extension argument to factor() or by specifying the domain explicitly.

>>> from sympy import factor, QQ
>>> factor(x**2 - 2)
x**2 - 2
>>> factor(x**2 - 2, extension=sqrt(2))
(x - sqrt(2))*(x + sqrt(2))
>>> factor(x**2 - 2, domain='QQ<sqrt(2)>')
(x - sqrt(2))*(x + sqrt(2))
>>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2)))
(x - sqrt(2))*(x + sqrt(2))

The extension=True argument can be used but will only create an extension that contains the coefficients which is usually not enough to factorise the polynomial.

>>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2)
>>> factor(p)                         # treats sqrt(2) as a symbol
(x + sqrt(2))*(x**2 - 2)
>>> factor(p, extension=True)
(x - sqrt(2))*(x + sqrt(2))**2
>>> factor(x**2 - 2, extension=True)  # all rational coefficients
x**2 - 2

It is also possible to use QQ<a> with the cancel() and gcd() functions.

>>> from sympy import cancel, gcd
>>> cancel((x**2 - 2)/(x - sqrt(2)))
(x**2 - 2)/(x - sqrt(2))
>>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2))
x + sqrt(2)
>>> gcd(x**2 - 2, x - sqrt(2))
1
>>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2))
x - sqrt(2)

When using the domain directly QQ<a> can be used as a constructor to create instances which then support the operations +,-,*,**,/. The algebraic_field() method is used to construct a particular QQ<a> domain. The from_sympy() method can be used to create domain elements from normal SymPy expressions.

>>> K = QQ.algebraic_field(sqrt(2))
>>> K
QQ<sqrt(2)>
>>> xk = K.from_sympy(3 + 4*sqrt(2))
>>> xk  
ANP([4, 3], [1, 0, -2], QQ)

Elements of QQ<a> are instances of ANP which have limited printing support. The raw display shows the internal representation of the element as the list [4, 3] representing the coefficients of 1 and sqrt(2) for this element in the form a * sqrt(2) + b * 1 where a and b are elements of QQ. The minimal polynomial for the generator (x**2 - 2) is also shown in the DUP representation as the list [1, 0, -2]. We can use to_sympy() to get a better printed form for the elements and to see the results of operations.

>>> xk = K.from_sympy(3 + 4*sqrt(2))
>>> yk = K.from_sympy(2 + 3*sqrt(2))
>>> xk * yk  
ANP([17, 30], [1, 0, -2], QQ)
>>> K.to_sympy(xk * yk)
17*sqrt(2) + 30
>>> K.to_sympy(xk + yk)
5 + 7*sqrt(2)
>>> K.to_sympy(xk ** 2)
24*sqrt(2) + 41
>>> K.to_sympy(xk / yk)
sqrt(2)/14 + 9/7

Any expression representing an algebraic number can be used to generate a QQ<a> domain provided its minimal polynomial can be computed. The function minpoly() function is used for this.

>>> from sympy import exp, I, pi, minpoly
>>> g = exp(2*I*pi/3)
>>> g
exp(2*I*pi/3)
>>> g.is_algebraic
True
>>> minpoly(g, x)
x**2 + x + 1
>>> factor(x**3 - 1, extension=g)
(x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3))

It is also possible to make an algebraic field from multiple extension elements.

>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K
QQ<sqrt(2) + sqrt(3)>
>>> p = x**4 - 5*x**2 + 6
>>> factor(p)
(x**2 - 3)*(x**2 - 2)
>>> factor(p, domain=K)
(x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
>>> factor(p, extension=[sqrt(2), sqrt(3)])
(x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))

Multiple extension elements are always combined together to make a single primitive element. In the case of [sqrt(2), sqrt(3)] the primitive element chosen is sqrt(2) + sqrt(3) which is why the domain displays as QQ<sqrt(2) + sqrt(3)>. The minimal polynomial for the primitive element is computed using the primitive_element() function.

>>> from sympy import primitive_element
>>> primitive_element([sqrt(2), sqrt(3)], x)
(x**4 - 10*x**2 + 1, [1, 1])
>>> minpoly(sqrt(2) + sqrt(3), x)
x**4 - 10*x**2 + 1

The extension elements that generate the domain can be accessed from the domain using the ext and orig_ext attributes as instances of AlgebraicNumber. The minimal polynomial for the primitive element as a DMP instance is available as mod.

>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K
QQ<sqrt(2) + sqrt(3)>
>>> K.ext
sqrt(2) + sqrt(3)
>>> K.orig_ext
(sqrt(2), sqrt(3))
>>> K.mod
DMP([1, 0, -10, 0, 1], QQ, None)

The discriminant of the field can be obtained from the discriminant() method, and an integral basis from the integral_basis() method. The latter returns a list of ANP instances by default, but can be made to return instances of Expr or AlgebraicNumber by passing a fmt argument. The maximal order, or ring of integers, of the field can also be obtained from the maximal_order() method, as a Submodule.

>>> zeta5 = exp(2*I*pi/5)
>>> K = QQ.algebraic_field(zeta5)
>>> K
QQ<exp(2*I*pi/5)>
>>> K.discriminant()
125
>>> K = QQ.algebraic_field(sqrt(5))
>>> K
QQ<sqrt(5)>
>>> K.integral_basis(fmt='sympy')
[1, 1/2 + sqrt(5)/2]
>>> K.maximal_order()
Submodule[[2, 0], [1, 1]]/2

The factorization of a rational prime into prime ideals of the field is computed by the primes_above() method, which returns a list of PrimeIdeal instances.

>>> zeta7 = exp(2*I*pi/7)
>>> K = QQ.algebraic_field(zeta7)
>>> K
QQ<exp(2*I*pi/7)>
>>> K.primes_above(11)
[[ (11, _x**3 + 5*_x**2 + 4*_x - 1) e=1, f=3 ],
 [ (11, _x**3 - 4*_x**2 - 5*_x - 1) e=1, f=3 ]]

Notes

It is not currently possible to generate an algebraic extension over any domain other than QQ. Ideally it would be possible to generate extensions like QQ(x)(sqrt(x**2 - 2)). This is equivalent to the quotient ring QQ(x)[y]/(y**2 - x**2 + 2) and there are two implementations of this kind of quotient ring/extension in the QuotientRing and MonogenicFiniteExtension classes. Each of those implementations needs some work to make them fully usable though.

algebraic_field(*extension)[source]

Returns an algebraic field, i.e. \(\mathbb{Q}(\alpha, \ldots)\).

denom(a)[source]

Returns denominator of a.

discriminant()[source]

Get the discriminant of the field.

dtype[source]

alias of ANP

ext

Primitive element used for the extension.

>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K.ext
sqrt(2) + sqrt(3)
from_AlgebraicField(a, K0)[source]

Convert AlgebraicField element ‘a’ to another AlgebraicField

from_GaussianIntegerRing(a, K0)[source]

Convert a GaussianInteger element ‘a’ to dtype.

from_GaussianRationalField(a, K0)[source]

Convert a GaussianRational element ‘a’ to dtype.

from_QQ(a, K0)[source]

Convert a Python Fraction object to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_ZZ(a, K0)[source]

Convert a Python int object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert SymPy’s expression to dtype.

get_ring()[source]

Returns a ring associated with self.

integral_basis(fmt=None)[source]

Get an integral basis for the field.

Parameters:

fmt : str, None, optional (default=None)

If None, return a list of ANP instances. If "sympy", convert each element of the list to an Expr, using self.to_sympy(). If "alg", convert each element of the list to an AlgebraicNumber, using self.to_alg_num().

Examples

>>> from sympy import QQ, AlgebraicNumber, sqrt
>>> alpha = AlgebraicNumber(sqrt(5), alias='alpha')
>>> k = QQ.algebraic_field(alpha)
>>> B0 = k.integral_basis()
>>> B1 = k.integral_basis(fmt='sympy')
>>> B2 = k.integral_basis(fmt='alg')
>>> print(B0[1])  
ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ)
>>> print(B1[1])
1/2 + alpha/2
>>> print(B2[1])
alpha/2 + 1/2

In the last two cases we get legible expressions, which print somewhat differently because of the different types involved:

>>> print(type(B1[1]))
<class 'sympy.core.add.Add'>
>>> print(type(B2[1]))
<class 'sympy.core.numbers.AlgebraicNumber'>
is_negative(a)[source]

Returns True if a is negative.

is_nonnegative(a)[source]

Returns True if a is non-negative.

is_nonpositive(a)[source]

Returns True if a is non-positive.

is_positive(a)[source]

Returns True if a is positive.

maximal_order()[source]

Compute the maximal order, or ring of integers, of the field.

Returns:

Submodule.

See also

integral_basis

mod

Minimal polynomial for the primitive element of the extension.

>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2))
>>> K.mod
DMP([1, 0, -2], QQ, None)
numer(a)[source]

Returns numerator of a.

orig_ext

Original elements given to generate the extension.

>>> from sympy import QQ, sqrt
>>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
>>> K.orig_ext
(sqrt(2), sqrt(3))
primes_above(p)[source]

Compute the prime ideals lying above a given rational prime p.

to_alg_num(a)[source]

Convert a of dtype to an AlgebraicNumber.

to_sympy(a)[source]

Convert a of dtype to a SymPy object.

RR

class sympy.polys.domains.RealField(prec=53, dps=None, tol=None)[source]

Real numbers up to the given precision.

almosteq(a, b, tolerance=None)[source]

Check if a and b are almost equal.

from_sympy(expr)[source]

Convert SymPy’s number to dtype.

gcd(a, b)[source]

Returns GCD of a and b.

get_exact()[source]

Returns an exact domain associated with self.

get_ring()[source]

Returns a ring associated with self.

lcm(a, b)[source]

Returns LCM of a and b.

to_rational(element, limit=True)[source]

Convert a real number to rational number.

to_sympy(element)[source]

Convert element to SymPy number.

class sympy.polys.domains.mpelements.RealElement(val=(0, 0, 0, 0), **kwargs)[source]

An element of a real domain.

CC

class sympy.polys.domains.ComplexField(prec=53, dps=None, tol=None)[source]

Complex numbers up to the given precision.

almosteq(a, b, tolerance=None)[source]

Check if a and b are almost equal.

from_sympy(expr)[source]

Convert SymPy’s number to dtype.

gcd(a, b)[source]

Returns GCD of a and b.

get_exact()[source]

Returns an exact domain associated with self.

get_ring()[source]

Returns a ring associated with self.

is_negative(element)[source]

Returns False for any ComplexElement.

is_nonnegative(element)[source]

Returns False for any ComplexElement.

is_nonpositive(element)[source]

Returns False for any ComplexElement.

is_positive(element)[source]

Returns False for any ComplexElement.

lcm(a, b)[source]

Returns LCM of a and b.

to_sympy(element)[source]

Convert element to SymPy number.

class sympy.polys.domains.mpelements.ComplexElement(real=0, imag=0)[source]

An element of a complex domain.

K[x]

class sympy.polys.domains.PolynomialRing(domain_or_ring, symbols=None, order=None)[source]

A class for representing multivariate polynomial rings.

factorial(a)[source]

Returns factorial of \(a\).

from_AlgebraicField(a, K0)[source]

Convert an algebraic number to dtype.

from_ComplexField(a, K0)[source]

Convert a mpmath \(mpf\) object to \(dtype\).

from_FractionField(a, K0)[source]

Convert a rational function to dtype.

from_GaussianIntegerRing(a, K0)[source]

Convert a \(GaussianInteger\) object to \(dtype\).

from_GaussianRationalField(a, K0)[source]

Convert a \(GaussianRational\) object to \(dtype\).

from_GlobalPolynomialRing(a, K0)[source]

Convert from old poly ring to dtype.

from_PolynomialRing(a, K0)[source]

Convert a polynomial to dtype.

from_QQ(a, K0)[source]

Convert a Python \(Fraction\) object to \(dtype\).

from_QQ_gmpy(a, K0)[source]

Convert a GMPY \(mpq\) object to \(dtype\).

from_QQ_python(a, K0)[source]

Convert a Python \(Fraction\) object to \(dtype\).

from_RealField(a, K0)[source]

Convert a mpmath \(mpf\) object to \(dtype\).

from_ZZ(a, K0)[source]

Convert a Python \(int\) object to \(dtype\).

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY \(mpz\) object to \(dtype\).

from_ZZ_python(a, K0)[source]

Convert a Python \(int\) object to \(dtype\).

from_sympy(a)[source]

Convert SymPy’s expression to \(dtype\).

gcd(a, b)[source]

Returns GCD of \(a\) and \(b\).

gcdex(a, b)[source]

Extended GCD of \(a\) and \(b\).

get_field()[source]

Returns a field associated with \(self\).

is_negative(a)[source]

Returns True if \(LC(a)\) is negative.

is_nonnegative(a)[source]

Returns True if \(LC(a)\) is non-negative.

is_nonpositive(a)[source]

Returns True if \(LC(a)\) is non-positive.

is_positive(a)[source]

Returns True if \(LC(a)\) is positive.

is_unit(a)[source]

Returns True if a is a unit of self

lcm(a, b)[source]

Returns LCM of \(a\) and \(b\).

to_sympy(a)[source]

Convert \(a\) to a SymPy object.

K(x)

class sympy.polys.domains.FractionField(domain_or_field, symbols=None, order=None)[source]

A class for representing multivariate rational function fields.

denom(a)[source]

Returns denominator of a.

factorial(a)[source]

Returns factorial of a.

from_AlgebraicField(a, K0)[source]

Convert an algebraic number to dtype.

from_ComplexField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_FractionField(a, K0)[source]

Convert a rational function to dtype.

from_GaussianIntegerRing(a, K0)[source]

Convert a GaussianInteger object to dtype.

from_GaussianRationalField(a, K0)[source]

Convert a GaussianRational object to dtype.

from_PolynomialRing(a, K0)[source]

Convert a polynomial to dtype.

from_QQ(a, K0)[source]

Convert a Python Fraction object to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_ZZ(a, K0)[source]

Convert a Python int object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert SymPy’s expression to dtype.

get_ring()[source]

Returns a field associated with self.

is_negative(a)[source]

Returns True if LC(a) is negative.

is_nonnegative(a)[source]

Returns True if LC(a) is non-negative.

is_nonpositive(a)[source]

Returns True if LC(a) is non-positive.

is_positive(a)[source]

Returns True if LC(a) is positive.

numer(a)[source]

Returns numerator of a.

to_sympy(a)[source]

Convert a to a SymPy object.

EX

class sympy.polys.domains.ExpressionDomain[source]

A class for arbitrary expressions.

class Expression(ex)[source]

An arbitrary expression.

denom(a)[source]

Returns denominator of a.

dtype[source]

alias of Expression

from_ExpressionDomain(a, K0)[source]

Convert a EX object to dtype.

from_FractionField(a, K0)[source]

Convert a DMF object to dtype.

from_GaussianIntegerRing(a, K0)[source]

Convert a GaussianRational object to dtype.

from_GaussianRationalField(a, K0)[source]

Convert a GaussianRational object to dtype.

from_PolynomialRing(a, K0)[source]

Convert a DMP object to dtype.

from_QQ(a, K0)[source]

Convert a Python Fraction object to dtype.

from_QQ_gmpy(a, K0)[source]

Convert a GMPY mpq object to dtype.

from_QQ_python(a, K0)[source]

Convert a Python Fraction object to dtype.

from_RealField(a, K0)[source]

Convert a mpmath mpf object to dtype.

from_ZZ(a, K0)[source]

Convert a Python int object to dtype.

from_ZZ_gmpy(a, K0)[source]

Convert a GMPY mpz object to dtype.

from_ZZ_python(a, K0)[source]

Convert a Python int object to dtype.

from_sympy(a)[source]

Convert SymPy’s expression to dtype.

get_field()[source]

Returns a field associated with self.

get_ring()[source]

Returns a ring associated with self.

is_negative(a)[source]

Returns True if a is negative.

is_nonnegative(a)[source]

Returns True if a is non-negative.

is_nonpositive(a)[source]

Returns True if a is non-positive.

is_positive(a)[source]

Returns True if a is positive.

numer(a)[source]

Returns numerator of a.

to_sympy(a)[source]

Convert a to a SymPy object.

class ExpressionDomain.Expression(ex)[source]

An arbitrary expression.

Quotient ring

class sympy.polys.domains.quotientring.QuotientRing(ring, ideal)[source]

Class representing (commutative) quotient rings.

You should not usually instantiate this by hand, instead use the constructor from the base ring in the construction.

>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**3 + 1)
>>> QQ.old_poly_ring(x).quotient_ring(I)
QQ[x]/<x**3 + 1>

Shorter versions are possible:

>>> QQ.old_poly_ring(x)/I
QQ[x]/<x**3 + 1>
>>> QQ.old_poly_ring(x)/[x**3 + 1]
QQ[x]/<x**3 + 1>

Attributes:

  • ring - the base ring

  • base_ideal - the ideal used to form the quotient

Sparse polynomials

Sparse polynomials are represented as dictionaries.

sympy.polys.rings.ring(symbols, domain, order=LexOrder())[source]

Construct a polynomial ring returning (ring, x_1, ..., x_n).

Parameters:

symbols : str

Symbol/Expr or sequence of str, Symbol/Expr (non-empty)

domain : Domain or coercible

order : MonomialOrder or coercible, optional, defaults to lex

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> R, x, y, z = ring("x,y,z", ZZ, lex)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
sympy.polys.rings.xring(symbols, domain, order=LexOrder())[source]

Construct a polynomial ring returning (ring, (x_1, ..., x_n)).

Parameters:

symbols : str

Symbol/Expr or sequence of str, Symbol/Expr (non-empty)

domain : Domain or coercible

order : MonomialOrder or coercible, optional, defaults to lex

Examples

>>> from sympy.polys.rings import xring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> R, (x, y, z) = xring("x,y,z", ZZ, lex)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
sympy.polys.rings.vring(symbols, domain, order=LexOrder())[source]

Construct a polynomial ring and inject x_1, ..., x_n into the global namespace.

Parameters:

symbols : str

Symbol/Expr or sequence of str, Symbol/Expr (non-empty)

domain : Domain or coercible

order : MonomialOrder or coercible, optional, defaults to lex

Examples

>>> from sympy.polys.rings import vring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex
>>> vring("x,y,z", ZZ, lex)
Polynomial ring in x, y, z over ZZ with lex order
>>> x + y + z # noqa:
x + y + z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
sympy.polys.rings.sring(exprs, *symbols, **options)[source]

Construct a ring deriving generators and domain from options and input expressions.

Parameters:

exprs : Expr or sequence of Expr (sympifiable)

symbols : sequence of Symbol/Expr

options : keyword arguments understood by Options

Examples

>>> from sympy import sring, symbols
>>> x, y, z = symbols("x,y,z")
>>> R, f = sring(x + 2*y + 3*z)
>>> R
Polynomial ring in x, y, z over ZZ with lex order
>>> f
x + 2*y + 3*z
>>> type(_)
<class 'sympy.polys.rings.PolyElement'>
class sympy.polys.rings.PolyRing(symbols, domain, order=LexOrder())[source]

Multivariate distributed polynomial ring.

add(*objs)[source]

Add a sequence of polynomials or containers of polynomials.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> R, x = ring("x", ZZ)
>>> R.add([ x**2 + 2*i + 3 for i in range(4) ])
4*x**2 + 24
>>> _.factor_list()
(4, [(x**2 + 6, 1)])
add_gens(symbols)[source]

Add the elements of symbols as generators to self

compose(other)[source]

Add the generators of other to self

drop(*gens)[source]

Remove specified generators from this ring.

drop_to_ground(*gens)[source]

Remove specified generators from the ring and inject them into its domain.

index(gen)[source]

Compute index of gen in self.gens.

monomial_basis(i)[source]

Return the ith-basis element.

mul(*objs)[source]

Multiply a sequence of polynomials or containers of polynomials.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> R, x = ring("x", ZZ)
>>> R.mul([ x**2 + 2*i + 3 for i in range(4) ])
x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945
>>> _.factor_list()
(1, [(x**2 + 3, 1), (x**2 + 5, 1), (x**2 + 7, 1), (x**2 + 9, 1)])
class sympy.polys.rings.PolyElement[source]

Element of multivariate distributed polynomial ring.

almosteq(p2, tolerance=None)[source]

Approximate equality test for polynomials.

cancel(g)[source]

Cancel common factors in a rational function f/g.

Examples

>>> from sympy.polys import ring, ZZ
>>> R, x,y = ring("x,y", ZZ)
>>> (2*x**2 - 2).cancel(x**2 - 2*x + 1)
(2*x + 2, x - 1)
coeff(element)[source]

Returns the coefficient that stands next to the given monomial.

Parameters:

element : PolyElement (with is_monomial = True) or 1

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = ring("x,y,z", ZZ)
>>> f = 3*x**2*y - x*y*z + 7*z**3 + 23
>>> f.coeff(x**2*y)
3
>>> f.coeff(x*y)
0
>>> f.coeff(1)
23
coeffs(order=None)[source]

Ordered list of polynomial coefficients.

Parameters:

order : MonomialOrder or coercible, optional

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.coeffs()
[2, 1]
>>> f.coeffs(grlex)
[1, 2]
const()[source]

Returns the constant coeffcient.

content()[source]

Returns GCD of polynomial’s coefficients.

copy()[source]

Return a copy of polynomial self.

Polynomials are mutable; if one is interested in preserving a polynomial, and one plans to use inplace operations, one can copy the polynomial. This method makes a shallow copy.

Examples

>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> R, x, y = ring('x, y', ZZ)
>>> p = (x + y)**2
>>> p1 = p.copy()
>>> p2 = p
>>> p[R.zero_monom] = 3
>>> p
x**2 + 2*x*y + y**2 + 3
>>> p1
x**2 + 2*x*y + y**2
>>> p2
x**2 + 2*x*y + y**2 + 3
degree(x=None)[source]

The leading degree in x or the main variable.

Note that the degree of 0 is negative infinity (the SymPy object -oo).

degrees()[source]

A tuple containing leading degrees in all variables.

Note that the degree of 0 is negative infinity (the SymPy object -oo)

diff(x)[source]

Computes partial derivative in x.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring("x,y", ZZ)
>>> p = x + x**2*y**3
>>> p.diff(x)
2*x*y**3 + 1
div(fv)[source]

Division algorithm, see [CLO] p64.

fv array of polynomials

return qv, r such that self = sum(fv[i]*qv[i]) + r

All polynomials are required not to be Laurent polynomials.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> f = x**3
>>> f0 = x - y**2
>>> f1 = x - y
>>> qv, r = f.div((f0, f1))
>>> qv[0]
x**2 + x*y**2 + y**4
>>> qv[1]
0
>>> r
y**6
imul_num(c)[source]

multiply inplace the polynomial p by an element in the coefficient ring, provided p is not one of the generators; else multiply not inplace

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y**2
>>> p1 = p.imul_num(3)
>>> p1
3*x + 3*y**2
>>> p1 is p
True
>>> p = x
>>> p1 = p.imul_num(3)
>>> p1
3*x
>>> p1 is p
False
itercoeffs()[source]

Iterator over coefficients of a polynomial.

itermonoms()[source]

Iterator over monomials of a polynomial.

iterterms()[source]

Iterator over terms of a polynomial.

leading_expv()[source]

Leading monomial tuple according to the monomial ordering.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = ring('x, y, z', ZZ)
>>> p = x**4 + x**3*y + x**2*z**2 + z**7
>>> p.leading_expv()
(4, 0, 0)
leading_monom()[source]

Leading monomial as a polynomial element.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> (3*x*y + y**2).leading_monom()
x*y
leading_term()[source]

Leading term as a polynomial element.

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> (3*x*y + y**2).leading_term()
3*x*y
listcoeffs()[source]

Unordered list of polynomial coefficients.

listmonoms()[source]

Unordered list of polynomial monomials.

listterms()[source]

Unordered list of polynomial terms.

monic()[source]

Divides all coefficients by the leading coefficient.

monoms(order=None)[source]

Ordered list of polynomial monomials.

Parameters:

order : MonomialOrder or coercible, optional

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.monoms()
[(2, 3), (1, 7)]
>>> f.monoms(grlex)
[(1, 7), (2, 3)]
primitive()[source]

Returns content and a primitive polynomial.

square()[source]

square of a polynomial

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> _, x, y = ring('x, y', ZZ)
>>> p = x + y**2
>>> p.square()
x**2 + 2*x*y**2 + y**4
strip_zero()[source]

Eliminate monomials with zero coefficient.

tail_degree(x=None)[source]

The tail degree in x or the main variable.

Note that the degree of 0 is negative infinity (the SymPy object -oo)

tail_degrees()[source]

A tuple containing tail degrees in all variables.

Note that the degree of 0 is negative infinity (the SymPy object -oo)

terms(order=None)[source]

Ordered list of polynomial terms.

Parameters:

order : MonomialOrder or coercible, optional

Examples

>>> from sympy.polys.rings import ring
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.orderings import lex, grlex
>>> _, x, y = ring("x, y", ZZ, lex)
>>> f = x*y**7 + 2*x**2*y**3
>>> f.terms()
[((2, 3), 2), ((1, 7), 1)]
>>> f.terms(grlex)
[((1, 7), 1), ((2, 3), 2)]

Sparse rational functions

Sparse polynomials are represented as dictionaries.

sympy.polys.fields.field(symbols, domain, order=LexOrder())[source]

Construct new rational function field returning (field, x1, …, xn).

sympy.polys.fields.xfield(symbols, domain, order=LexOrder())[source]

Construct new rational function field returning (field, (x1, …, xn)).

sympy.polys.fields.vfield(symbols, domain, order=LexOrder())[source]

Construct new rational function field and inject generators into global namespace.

sympy.polys.fields.sfield(exprs, *symbols, **options)[source]

Construct a field deriving generators and domain from options and input expressions.

Parameters:

exprs : py:class:\(~.Expr\) or sequence of Expr (sympifiable)

symbols : sequence of Symbol/Expr

options : keyword arguments understood by Options

Examples

>>> from sympy import exp, log, symbols, sfield
>>> x = symbols("x")
>>> K, f = sfield((x*log(x) + 4*x**2)*exp(1/x + log(x)/3)/x**2)
>>> K
Rational function field in x, exp(1/x), log(x), x**(1/3) over ZZ with lex order
>>> f
(4*x**2*(exp(1/x)) + x*(exp(1/x))*(log(x)))/((x**(1/3))**5)
class sympy.polys.fields.FracField(symbols, domain, order=LexOrder())[source]

Multivariate distributed rational function field.

class sympy.polys.fields.FracElement(numer, denom=None)[source]

Element of multivariate distributed rational function field.

diff(x)[source]

Computes partial derivative in x.

Examples

>>> from sympy.polys.fields import field
>>> from sympy.polys.domains import ZZ
>>> _, x, y, z = field("x,y,z", ZZ)
>>> ((x**2 + y)/(z + 1)).diff(x)
2*x/(z + 1)

Dense polynomials

class sympy.polys.polyclasses.DMP(rep, dom, lev=None, ring=None)[source]

Dense Multivariate Polynomials over \(K\).

LC()[source]

Returns the leading coefficient of f.

TC()[source]

Returns the trailing coefficient of f.

abs()[source]

Make all coefficients in f positive.

add(g)[source]

Add two multivariate polynomials f and g.

add_ground(c)[source]

Add an element of the ground domain to f.

all_coeffs()[source]

Returns all coefficients from f.

all_monoms()[source]

Returns all monomials from f.

all_terms()[source]

Returns all terms from a f.

cancel(g, include=True)[source]

Cancel common factors in a rational function f/g.

cauchy_lower_bound()[source]

Computes the Cauchy lower bound on the nonzero roots of f.

cauchy_upper_bound()[source]

Computes the Cauchy upper bound on the roots of f.

clear_denoms()[source]

Clear denominators, but keep the ground domain.

coeffs(order=None)[source]

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

cofactors(g)[source]

Returns GCD of f and g and their cofactors.

compose(g)[source]

Computes functional composition of f and g.

content()[source]

Returns GCD of polynomial coefficients.

convert(dom)[source]

Convert the ground domain of f.

count_complex_roots(inf=None, sup=None)[source]

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

count_real_roots(inf=None, sup=None)[source]

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

decompose()[source]

Computes functional decomposition of f.

deflate()[source]

Reduce degree of \(f\) by mapping \(x_i^m\) to \(y_i\).

degree(j=0)[source]

Returns the leading degree of f in x_j.

degree_list()[source]

Returns a list of degrees of f.

diff(m=1, j=0)[source]

Computes the m-th order derivative of f in x_j.

discriminant()[source]

Computes discriminant of f.

div(g)[source]

Polynomial division with remainder of f and g.

eject(dom, front=False)[source]

Eject selected generators into the ground domain.

eval(a, j=0)[source]

Evaluates f at the given point a in x_j.

exclude()[source]

Remove useless generators from f.

Returns the removed generators and the new excluded f.

Examples

>>> from sympy.polys.polyclasses import DMP
>>> from sympy.polys.domains import ZZ
>>> DMP([[[ZZ(1)]], [[ZZ(1)], [ZZ(2)]]], ZZ).exclude()
([2], DMP([[1], [1, 2]], ZZ, None))
exquo(g)[source]

Computes polynomial exact quotient of f and g.

exquo_ground(c)[source]

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

factor_list()[source]

Returns a list of irreducible factors of f.

factor_list_include()[source]

Returns a list of irreducible factors of f.

classmethod from_dict(rep, lev, dom)[source]

Construct and instance of cls from a dict representation.

classmethod from_list(rep, lev, dom)[source]

Create an instance of cls given a list of native coefficients.

classmethod from_sympy_list(rep, lev, dom)[source]

Create an instance of cls given a list of SymPy coefficients.

gcd(g)[source]

Returns polynomial GCD of f and g.

gcdex(g)[source]

Extended Euclidean algorithm, if univariate.

gff_list()[source]

Computes greatest factorial factorization of f.

half_gcdex(g)[source]

Half extended Euclidean algorithm, if univariate.

homogeneous_order()[source]

Returns the homogeneous order of f.

homogenize(s)[source]

Return homogeneous polynomial of f

inject(front=False)[source]

Inject ground domain generators into f.

integrate(m=1, j=0)[source]

Computes the m-th order indefinite integral of f in x_j.

intervals(all=False, eps=None, inf=None, sup=None, fast=False, sqf=False)[source]

Compute isolating intervals for roots of f.

invert(g)[source]

Invert f modulo g, if possible.

property is_cyclotomic

Returns True if f is a cyclotomic polynomial.

property is_ground

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

property is_homogeneous

Returns True if f is a homogeneous polynomial.

property is_irreducible

Returns True if f has no factors over its domain.

property is_linear

Returns True if f is linear in all its variables.

property is_monic

Returns True if the leading coefficient of f is one.

property is_monomial

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

property is_one

Returns True if f is a unit polynomial.

property is_primitive

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

property is_quadratic

Returns True if f is quadratic in all its variables.

property is_sqf

Returns True if f is a square-free polynomial.

property is_zero

Returns True if f is a zero polynomial.

l1_norm()[source]

Returns l1 norm of f.

l2_norm_squared()[source]

Return squared l2 norm of f.

lcm(g)[source]

Returns polynomial LCM of f and g.

lift()[source]

Convert algebraic coefficients to rationals.

max_norm()[source]

Returns maximum norm of f.

mignotte_sep_bound_squared()[source]

Computes the squared Mignotte bound on root separations of f.

monic()[source]

Divides all coefficients by LC(f).

monoms(order=None)[source]

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

mul(g)[source]

Multiply two multivariate polynomials f and g.

mul_ground(c)[source]

Multiply f by a an element of the ground domain.

neg()[source]

Negate all coefficients in f.

norm()[source]

Computes Norm(f).

nth(*N)[source]

Returns the n-th coefficient of f.

pdiv(g)[source]

Polynomial pseudo-division of f and g.

per(rep, dom=None, kill=False, ring=None)[source]

Create a DMP out of the given representation.

permute(P)[source]

Returns a polynomial in \(K[x_{P(1)}, ..., x_{P(n)}]\).

Examples

>>> from sympy.polys.polyclasses import DMP
>>> from sympy.polys.domains import ZZ
>>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 0, 2])
DMP([[[2], []], [[1, 0], []]], ZZ, None)
>>> DMP([[[ZZ(2)], [ZZ(1), ZZ(0)]], [[]]], ZZ).permute([1, 2, 0])
DMP([[[1], []], [[2, 0], []]], ZZ, None)
pexquo(g)[source]

Polynomial exact pseudo-quotient of f and g.

pow(n)[source]

Raise f to a non-negative power n.

pquo(g)[source]

Polynomial pseudo-quotient of f and g.

prem(g)[source]

Polynomial pseudo-remainder of f and g.

primitive()[source]

Returns content and a primitive form of f.

quo(g)[source]

Computes polynomial quotient of f and g.

quo_ground(c)[source]

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

refine_root(s, t, eps=None, steps=None, fast=False)[source]

Refine an isolating interval to the given precision.

eps should be a rational number.

rem(g)[source]

Computes polynomial remainder of f and g.

resultant(g, includePRS=False)[source]

Computes resultant of f and g via PRS.

revert(n)[source]

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

shift(a)[source]

Efficiently compute Taylor shift f(x + a).

slice(m, n, j=0)[source]

Take a continuous subsequence of terms of f.

sqf_list(all=False)[source]

Returns a list of square-free factors of f.

sqf_list_include(all=False)[source]

Returns a list of square-free factors of f.

sqf_norm()[source]

Computes square-free norm of f.

sqf_part()[source]

Computes square-free part of f.

sqr()[source]

Square a multivariate polynomial f.

sturm()[source]

Computes the Sturm sequence of f.

sub(g)[source]

Subtract two multivariate polynomials f and g.

sub_ground(c)[source]

Subtract an element of the ground domain from f.

subresultants(g)[source]

Computes subresultant PRS sequence of f and g.

terms(order=None)[source]

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

terms_gcd()[source]

Remove GCD of terms from the polynomial f.

to_dict(zero=False)[source]

Convert f to a dict representation with native coefficients.

to_exact()[source]

Make the ground domain exact.

to_field()[source]

Make the ground domain a field.

to_list()[source]

Convert f to a list representation with native coefficients.

to_ring()[source]

Make the ground domain a ring.

to_sympy_dict(zero=False)[source]

Convert f to a dict representation with SymPy coefficients.

to_sympy_list()[source]

Convert f to a list representation with SymPy coefficients.

to_tuple()[source]

Convert f to a tuple representation with native coefficients.

This is needed for hashing.

total_degree()[source]

Returns the total degree of f.

transform(p, q)[source]

Evaluate functional transformation q**n * f(p/q).

trunc(p)[source]

Reduce f modulo a constant p.

unify(g)[source]

Unify representations of two multivariate polynomials.

class sympy.polys.polyclasses.DMF(rep, dom, lev=None, ring=None)[source]

Dense Multivariate Fractions over \(K\).

add(g)[source]

Add two multivariate fractions f and g.

cancel()[source]

Remove common factors from f.num and f.den.

denom()[source]

Returns the denominator of f.

exquo(g)[source]

Computes quotient of fractions f and g.

frac_unify(g)[source]

Unify representations of two multivariate fractions.

half_per(rep, kill=False)[source]

Create a DMP out of the given representation.

invert(check=True)[source]

Computes inverse of a fraction f.

property is_one

Returns True if f is a unit fraction.

property is_zero

Returns True if f is a zero fraction.

mul(g)[source]

Multiply two multivariate fractions f and g.

neg()[source]

Negate all coefficients in f.

numer()[source]

Returns the numerator of f.

per(num, den, cancel=True, kill=False, ring=None)[source]

Create a DMF out of the given representation.

poly_unify(g)[source]

Unify a multivariate fraction and a polynomial.

pow(n)[source]

Raise f to a non-negative power n.

quo(g)[source]

Computes quotient of fractions f and g.

sub(g)[source]

Subtract two multivariate fractions f and g.

class sympy.polys.polyclasses.ANP(rep, mod, dom)[source]

Dense Algebraic Number Polynomials over a field.

LC()[source]

Returns the leading coefficient of f.

TC()[source]

Returns the trailing coefficient of f.

property is_ground

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

property is_one

Returns True if f is a unit algebraic number.

property is_zero

Returns True if f is a zero algebraic number.

pow(n)[source]

Raise f to a non-negative power n.

to_dict()[source]

Convert f to a dict representation with native coefficients.

to_list()[source]

Convert f to a list representation with native coefficients.

to_sympy_dict()[source]

Convert f to a dict representation with SymPy coefficients.

to_sympy_list()[source]

Convert f to a list representation with SymPy coefficients.

to_tuple()[source]

Convert f to a tuple representation with native coefficients.

This is needed for hashing.

unify(g)[source]

Unify representations of two algebraic numbers.