# SymPy Core¶

## sympify¶

### sympify¶

sympy.core.sympify.sympify(a, locals=None, convert_xor=True, strict=False, rational=False)[source]

Converts an arbitrary expression to a type that can be used inside sympy.

For example, it will convert python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE.

It currently accepts as arguments:
• any object defined in sympy (except matrices [TODO])
• standard numeric python types: int, long, float, Decimal
• strings (like “0.09” or “2e-19”)
• booleans, including None (will leave them unchanged)
• lists, sets or tuples containing any of the above

If the argument is already a type that sympy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type.

>>> from sympy import sympify

>>> sympify(2).is_integer
True
>>> sympify(2).is_real
True

>>> sympify(2.0).is_real
True
>>> sympify("2.0").is_real
True
>>> sympify("2e-45").is_real
True


If the expression could not be converted, a SympifyError is raised.

>>> sympify("x***2")
Traceback (most recent call last):
...
SympifyError: SympifyError: "could not parse u'x***2'"


If the option strict is set to True, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.

>>> sympify(True)
True
>>> sympify(True, strict=True)
Traceback (most recent call last):
...
SympifyError: SympifyError: True


To extend sympify to convert custom objects (not derived from Basic), just define a _sympy_ method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime.

>>> from sympy import Matrix
>>> class MyList1(object):
...     def __iter__(self):
...         yield 1
...         yield 2
...         raise StopIteration
...     def __getitem__(self, i): return list(self)[i]
...     def _sympy_(self): return Matrix(self)
>>> sympify(MyList1())
[1]
[2]


If you do not have control over the class definition you could also use the converter global dictionary. The key is the class and the value is a function that takes a single argument and returns the desired SymPy object, e.g. converter[MyList] = lambda x: Matrix(x).

>>> class MyList2(object):   # XXX Do not do this if you control the class!
...     def __iter__(self):  #     Use _sympy_!
...         yield 1
...         yield 2
...         raise StopIteration
...     def __getitem__(self, i): return list(self)[i]
>>> from sympy.core.sympify import converter
>>> converter[MyList2] = lambda x: Matrix(x)
>>> sympify(MyList2())
[1]
[2]


## cache¶

### cacheit¶

sympy.core.cache.cacheit(func)

caching decorator.

important: the result of cached function must be immutable

Examples

>>> from sympy.core.cache import cacheit
>>> @cacheit
... def f(a,b):
...    return a+b

>>> @cacheit
... def f(a,b):
...    return [a,b] # <-- WRONG, returns mutable object


to force cacheit to check returned results mutability and consistency, set environment variable SYMPY_USE_CACHE to ‘debug’

## basic¶

### Basic¶

class sympy.core.basic.Basic[source]

Base class for all objects in sympy.

Conventions:

1. Always use .args, when accessing parameters of some instance:

>>> from sympy import symbols, cot
>>> from sympy.abc import x, y

>>> cot(x).args
(x,)

>>> cot(x).args[0]
x

>>> (x*y).args
(x, y)

>>> (x*y).args[1]
y

2. Never use internal methods or variables (the ones prefixed with _):

>>> cot(x)._args    # do not use this, use cot(x).args instead
(x,)

args[source]

Returns a tuple of arguments of ‘self’.

Notes

Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

Examples

>>> from sympy import symbols, cot
>>> from sympy.abc import x, y

>>> cot(x).args
(x,)

>>> cot(x).args[0]
x

>>> (x*y).args
(x, y)

>>> (x*y).args[1]
y


A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.

See docstring of Expr.as_content_primitive

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

Converts self to a polynomial or returns None.

>>> from sympy import Poly, 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

assumptions0[source]

Return object $$type$$ assumptions.

For example:

Symbol(‘x’, real=True) Symbol(‘x’, integer=True)

are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo.

Examples

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'hermitian': True,
'imaginary': False, 'negative': False, 'nonnegative': True,
'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True,
'zero': False}

atoms(*types)[source]

Returns the atoms that form the current object.

By default, only objects that are truly atomic and can’t be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below.

Examples

>>> from sympy import Number, NumberSymbol, Symbol
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
set([x, y])

>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
set([1, 2])

>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
set([1, 2, pi])

>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
set([1, 2, I, pi])


Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class.

The type can be given implicitly, too:

>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
set([x, y])


Be careful to check your assumptions when using the implicit option since S(1).is_Integer = True but type(S(1)) is One, a special type of sympy atom, while type(S(2)) is type Integer and will find all integers in an expression:

>>> from sympy import S
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
set([1])

>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
set([1, 2])


Finally, arguments to atoms() can select more than atomic atoms: any sympy type (loaded in core/__init__.py) can be listed as an argument and those types of “atoms” as found in scanning the arguments of the expression recursively:

>>> from sympy import Function, Mul
>>> from sympy.core.function import AppliedUndef
>>> f = Function('f')
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
set([f(x), sin(y + I*pi)])
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
set([f(x)])

>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])

classmethod class_key()[source]

Nice order of classes.

compare(other)[source]

Return -1, 0, 1 if the object is smaller, equal, or greater than other.

Not in the mathematical sense. If the object is of a different type from the “other” then their classes are ordered according to the sorted_classes list.

Examples

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1

static compare_pretty(*args, **kwargs)[source]

Is a > b in the sense of ordering in printing?

THIS FUNCTION IS DEPRECATED. Use default_sort_key instead.

yes ..... return 1
no ...... return -1
equal ... return 0

Strategy:

It uses Basic.compare as a fallback, but improves it in many cases, like x**3, x**4, O(x**3) etc. In those simple cases, it just parses the expression and returns the “sane” ordering such as:

1 < x < x**2 < x**3 < O(x**4) etc.

Examples

>>> from sympy.abc import x
>>> from sympy import Basic, Number
>>> Basic._compare_pretty(x, x**2)
-1
>>> Basic._compare_pretty(x**2, x**2)
0
>>> Basic._compare_pretty(x**3, x**2)
1
>>> Basic._compare_pretty(Number(1, 2), Number(1, 3))
1
>>> Basic._compare_pretty(Number(0), Number(-1))
1

count(query)[source]

Count the number of matching subexpressions.

count_ops(visual=None)[source]

wrapper for count_ops that returns the operation count.

doit(**hints)[source]

Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.

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

>>> 2*Integral(x, x)
2*Integral(x, x)

>>> (2*Integral(x, x)).doit()
x**2

>>> (2*Integral(x, x)).doit(deep = False)
2*Integral(x, x)

dummy_eq(other, symbol=None)[source]

Compare two expressions and handle dummy symbols.

Examples

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

>>> u = Dummy('u')

>>> (u**2 + 1).dummy_eq(x**2 + 1)
True
>>> (u**2 + 1) == (x**2 + 1)
False

>>> (u**2 + y).dummy_eq(x**2 + y, x)
True
>>> (u**2 + y).dummy_eq(x**2 + y, y)
False

find(query, group=False)[source]

Find all subexpressions matching a query.

free_symbols[source]

Return from the atoms of self those which are free symbols.

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own symbols method.

Any other method that uses bound variables should implement a symbols method.

classmethod fromiter(args, **assumptions)[source]

Create a new object from an iterable.

This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first.

Examples

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)

func[source]

The top-level function in an expression.

The following should hold for all objects:

>> x == x.func(*x.args)

Examples

>>> from sympy.abc import x
>>> a = 2*x
>>> a.func
<class 'sympy.core.mul.Mul'>
>>> a.args
(2, x)
>>> a.func(*a.args)
2*x
>>> a == a.func(*a.args)
True

has(*args, **kw_args)[source]

Test whether any subexpression matches any of the patterns.

Examples

>>> from sympy import sin, S
>>> from sympy.abc import x, y, z
>>> (x**2 + sin(x*y)).has(z)
False
>>> (x**2 + sin(x*y)).has(x, y, z)
True
>>> x.has(x)
True


Note that expr.has(*patterns) is exactly equivalent to any(expr.has(p) for p in patterns). In particular, False is returned when the list of patterns is empty.

>>> x.has()
False

is_Real[source]

Deprecated alias for is_Float

is_number[source]

Returns True if ‘self’ is a number.

>>> from sympy import log, Integral
>>> from sympy.abc import x, y

>>> x.is_number
False
>>> (2*x).is_number
False
>>> (2 + log(2)).is_number
True
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True

iter_basic_args()[source]

Iterates arguments of self.

Examples

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<...iterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]

match(pattern)[source]

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.xreplace(self.match(pattern)) == self


Examples

>>> from sympy import symbols, Wild
>>> from sympy.abc import x, y
>>> p = Wild("p")
>>> q = Wild("q")
>>> r = Wild("r")
>>> e = (x+y)**(x+y)
>>> e.match(p**p)
{p_: x + y}
>>> e.match(p**q)
{p_: x + y, q_: x + y}
>>> e = (2*x)**2
>>> e.match(p*q**r)
{p_: 4, q_: x, r_: 2}
>>> (p*q**r).xreplace(e.match(p*q**r))
4*x**2

matches(expr, repl_dict={})[source]

Helper method for match() - switches the pattern and expr.

Can be used to solve linear equations:

>>> from sympy import Symbol, Wild, Integer
>>> a,b = map(Symbol, 'ab')
>>> x = Wild('x')
>>> (a+b*x).matches(Integer(0))
{x_: -a/b}

replace(query, value, map=False)[source]

Replace matching subexpressions of self with value.

If map = True then also return the mapping {old: new} where old was a sub-expression found with query and new is the replacement value for it.

Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The list of possible combinations of queries and replacement values is listed below:

subs
substitution of subexpressions as defined by the objects themselves.
xreplace
exact node replacement in expr tree; also capable of using matching rules

Examples

Initial setup

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x, y
>>> f = log(sin(x)) + tan(sin(x**2))

1.1. type -> type

obj.replace(sin, tan)

>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})

1.2. type -> func

obj.replace(sin, lambda arg: ...)

>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))

2.1. expr -> expr

obj.replace(sin(a), tan(a))

>>> a = Wild('a')
>>> f.replace(sin(a), tan(a))
log(tan(x)) + tan(tan(x**2))

2.2. expr -> func

obj.replace(sin(a), lambda a: ...)

>>> f.replace(sin(a), cos(a))
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin(a), lambda a: sin(2*a))
log(sin(2*x)) + tan(sin(2*x**2))

3.1. func -> func

obj.replace(lambda expr: ..., lambda expr: ...)

>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)

rewrite(*args, **hints)[source]

Rewrites expression containing applications of functions of one kind in terms of functions of different kind. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function.

As a pattern this function accepts a list of functions to to rewrite (instances of DefinedFunction class). As rule you can use string or a destination function instance (in this case rewrite() will use the str() function).

There is also possibility to pass hints on how to rewrite the given expressions. For now there is only one such hint defined called ‘deep’. When ‘deep’ is set to False it will forbid functions to rewrite their contents.

>>> from sympy import sin, exp, I
>>> from sympy.abc import x, y

>>> sin(x).rewrite(sin, exp)
-I*(exp(I*x) - exp(-I*x))/2

sort_key(*args, **kw_args)[source]

Return a sort key.

Examples

>>> from sympy.core import Basic, S, I
>>> from sympy.abc import x

>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]

>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]

subs(*args, **kwargs)[source]

Substitutes old for new in an expression after sympifying args.

$$args$$ is either:
• two arguments, e.g. foo.subs(old, new)

• one iterable argument, e.g. foo.subs(iterable). The iterable may be
o an iterable container with (old, new) pairs. In this case the

replacements are processed in the order given with successive patterns possibly affecting replacements already made.

o a dict or set whose key/value items correspond to old/new pairs.

In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous).

If the keyword simultaneous is True, the subexpressions will not be evaluated until all the substitutions have been made.

replace
replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements
xreplace
exact node replacement in expr tree; also capable of using matching rules

Examples

>>> from sympy import pi, exp
>>> from sympy.abc import x, y
>>> (1 + x*y).subs(x, pi)
pi*y + 1
>>> (1 + x*y).subs({x:pi, y:2})
1 + 2*pi
>>> (1 + x*y).subs([(x, pi), (y, 2)])
1 + 2*pi
>>> reps = [(y, x**2), (x, 2)]
>>> (x + y).subs(reps)
6
>>> (x + y).subs(reversed(reps))
x**2 + 2

>>> (x**2 + x**4).subs(x**2, y)
y**2 + y


To replace only the x**2 but not the x**4, use xreplace:

>>> (x**2 + x**4).xreplace({x**2: y})
x**4 + y


To delay evaluation until all substitutions have been made, set the keyword simultaneous to True:

>>> (x/y).subs([(x, 0), (y, 0)])
0
>>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
nan


>>> ((x + y)/y).subs({x + y: y, y: x + y})
1
>>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
y/(x + y)


In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted.

>>> from sympy import sqrt, sin, cos, exp
>>> from sympy.abc import a, b, c, d, e

>>> A = (sqrt(sin(2*x)), a)
>>> B = (sin(2*x), b)
>>> C = (cos(2*x), c)
>>> D = (x, d)
>>> E = (exp(x), e)

>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)

>>> expr.subs(dict([A,B,C,D,E]))
a*c*sin(d*e) + b

xreplace(rule)[source]

Replace occurrences of objects within the expression.

Parameters : rule : dict-like Expresses a replacement rule xreplace : the result of the replacement

replace
replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements
subs
substitution of subexpressions as defined by the objects themselves.

Examples

>>> from sympy import symbols, pi, exp
>>> x, y, z = symbols('x y z')
>>> (1 + x*y).xreplace({x: pi})
pi*y + 1
>>> (1 + x*y).xreplace({x:pi, y:2})
1 + 2*pi


Replacements occur only if an entire node in the expression tree is matched:

>>> (x*y + z).xreplace({x*y: pi})
z + pi
>>> (x*y*z).xreplace({x*y: pi})
x*y*z
>>> (2*x).xreplace({2*x: y, x: z})
y
>>> (2*2*x).xreplace({2*x: y, x: z})
4*z
>>> (x + y + 2).xreplace({x + y: 2})
x + y + 2
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
x + exp(y) + 2


xreplace doesn’t differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:

>>> from sympy import Integral
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
Integral(y, (y, 1, 2*y))


Trying to replace x with an expression raises an error:

>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y})
ValueError: Invalid limits given: ((2*y, 1, 4*y),)


### Atom¶

class sympy.core.basic.Atom[source]

A parent class for atomic things. An atom is an expression with no subexpressions.

Examples

Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ...

### C¶

sympy.core.basic.C

## singleton¶

### S¶

sympy.core.singleton.S

## Expr¶

class sympy.core.expr.Expr[source]
apart(x=None, **args)[source]

See the apart function in sympy.polys

args_cnc(cset=False, warn=True)[source]

Return [commutative factors, non-commutative factors] of self.

self is treated as a Mul and the ordering of the factors is maintained. If cset is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly supressed by setting warn to False.

Note: -1 is always separated from a Number.

>>> from sympy import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[set([-1, 2, x, y]), []]


The arg is always treated as a Mul:

>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]


Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

Return the tuple (c, args) where self is written as an Add, a.

c should be a Rational added to any terms of the Add that are independent of deps.

args should be a tuple of all other terms of a; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.

• if you know self is an Add and want only the head, use self.args[0];
• if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.
• if you want to split self into an independent and dependent parts use self.as_independent(*deps)
>>> from sympy import S
>>> from sympy.abc import x, y
(3, ())
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
(y + 3, ())

as_coeff_exponent(x)[source]

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)[source]

as_coeff_mul(*deps)[source]

Return the tuple (c, args) where self is written as a Mul, m.

c should be a Rational multiplied by any terms of the Mul that are independent of deps.

args should be a tuple of all other terms of m; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you don’t know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.

• if you know self is a Mul and want only the head, use self.args[0];
• if you don’t want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;
• if you want to split self into an independent and dependent parts use self.as_independent(*deps)
>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())

as_coeff_terms(*deps)[source]

This method is deprecated. Use .as_coeff_mul() instead.

as_coefficient(expr)[source]

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into the product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

coeff

Examples

>>> from sympy import E, pi, sin, I, symbols
>>> from sympy.abc import x, y

>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)

>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> (2*E*x + x).as_coefficient(E)

>>> (E*(x + 1) + x).as_coefficient(E)

>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)

as_coefficients_dict()[source]

Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.

Examples

>>> from sympy.abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}


This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and Mul(*foo.as_content_primitive()) == foo. The primitive need no be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self).

Examples

>>> from sympy import sqrt
>>> from sympy.abc import x, y, z

>>> eq = 2 + 2*x + 2*y*(3 + 3*y)


The as_content_primitive function is recursive and retains structure:

>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)


Integer powers will have Rationals extracted from the base:

>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))


Terms may end up joining once their as_content_primitives are added:

>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((5*(x*(1 + y)) + 2.0*x*(3 + 3*y))**2).as_content_primitive()
(1, 121.0*x**2*(y + 1)**2)


Radical content can also be factored out of the primitive:

>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))

as_expr(*gens)[source]

Convert a polynomial to a SymPy expression.

Examples

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

>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y

>>> sin(x).as_expr()
sin(x)

as_independent(*deps, **hint)[source]

A mostly naive separation of a Mul or Add into arguments that are not are dependent on deps. To obtain as complete a separation of variables as possible, use a separation method first, e.g.:

• separatevars() to change Mul, Add and Pow (including exp) into Mul
• .expand(log=True) to change log expr into an Add

The only non-naive thing that is done here is to respect noncommutative ordering of variables.

The returned tuple (i, d) has the following interpretation:

• i will has no variable that appears in deps
• d will be 1 or else have terms that contain variables that are in deps
• if self is an Add then self = i + d
• if self is a Mul then self = i*d
• if self is anything else, either tuple (self, S.One) or (S.One, self) is returned.

To force the expression to be treated as an Add, use the hint as_Add=True

Examples

>>> from sympy import sin, cos, exp
>>> from sympy.abc import x, y, z

>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)


– self is a Mul

>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))


non-commutative terms cannot always be separated out when self is a Mul

>>> from sympy import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))


– self is anything else:

>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))


– force self to be treated as an Add:

>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)


– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
(1, x - 3)


Note how the below differs from the above in making the constant on the dep term positive.

>>> (y*(-3+x)).as_independent(x)
(y, x - 3)

– use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free symbols while the latter considers all symbols
>>> from sympy import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True


Note: when trying to get independent terms, a separation method might need to be used first. In this case, it is important to keep track of what you send to this routine so you know how to interpret the returned values

>>> from sympy import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b',positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))


Returns the leading (nonzero) term of the series expansion of self.

The _eval_as_leading_term routines are used to do this, and they must always return a non-zero value.

Examples

>>> from sympy.abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)

as_numer_denom()[source]

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

normal
return a/b instead of a, b
as_ordered_factors(order=None)[source]

Return list of ordered factors (if Mul) else [self].

as_ordered_terms(order=None, data=False)[source]

Transform an expression to an ordered list of terms.

Examples

>>> from sympy import sin, cos
>>> from sympy.abc import x, y

>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]

as_powers_dict()[source]

Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary.

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method can’t be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from sympy import symbols, I

>>> x, y = symbols('x,y', real=True)

>>> (x + y*I).as_real_imag()
(x, y)

>>> from sympy.abc import z, w

>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))

as_terms()[source]

Transform an expression to a list of terms.

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

See the cancel function in sympy.polys

coeff(x, n=1, right=False)[source]

Returns the coefficient from the term containing “x**n” or None if there is no such term. If n is zero then all terms independent of x will be returned.

When x is noncommutative, the coeff to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.

a method to separate the additive constant from an expression
as_coeff_Mul
a method to separate the multiplicative constant from an expression
as_independent
a method to separate x dependent terms/factors from others

Examples

>>> from sympy import symbols
>>> from sympy.abc import x, y, z


You can select terms that have an explicit negative in front of them:

>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y


You can select terms with no Rational coefficient:

>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0


You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None):

>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]


You can select terms that have a numerical term in front of them:

>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x


The matching is exact:

>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0


In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following:

>>> (x + z*(x + x*y)).coeff(x)
1


If such factoring is desired, factor_terms can be used first:

>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1

>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m


If there is more than one possible coefficient 0 is returned:

>>> (n*m + m*n).coeff(n)
0


If there is only one possible coefficient, it is returned:

>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1

collect(syms, func=None, evaluate=True, exact=False, distribute_order_term=True)[source]

See the collect function in sympy.simplify

combsimp()[source]

See the combsimp function in sympy.simplify

as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first. If skip_abs is true, the absolute term is assumed to be zero. (This is necessary because sometimes it cannot be simplified to zero without a lot of work, but is still known to be zero. See log._eval_nseries for an example.) If skip_log is true, log(x) is treated as an independent symbol. (This is needed for the gruntz algorithm.)

could_extract_minus_sign()[source]

Canonical way to choose an element in the set {e, -e} where e is any expression. If the canonical element is e, we have e.could_extract_minus_sign() == True, else e.could_extract_minus_sign() == False.

For any expression, the set {e.could_extract_minus_sign(), (-e).could_extract_minus_sign()} must be {True, False}.

>>> from sympy.abc import x, y
>>> (x-y).could_extract_minus_sign() != (y-x).could_extract_minus_sign()
True

count_ops(visual=None)[source]

wrapper for count_ops that returns the operation count.

equals(other, failing_expression=False)[source]

Return True if self == other, False if it doesn’t, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.

If self is a Number (or complex number) that is not zero, then the result is False.

If self is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either -1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False.

expand(*args, **kw_args)[source]

Expand an expression using hints.

See the docstring of the expand() function in sympy.core.function for more information.

Return self - c if it’s possible to subtract c from self and make all matching coefficients move towards zero, else return None.

Examples

>>> from sympy import S
>>> from sympy.abc import x, y
>>> e = 2*x + 3
x + 2
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3


Sometimes auto-expansion will return a less simplified result than desired; gcd_terms might be used in such cases:

>>> from sympy import gcd_terms
>>> (4*x*(y + 1) + y).extract_additively(x)
4*x*(y + 1) + x*(4*y + 3) - x*(4*y + 4) + y
>>> gcd_terms(_)
x*(4*y + 3) + y

extract_branch_factor(allow_half=False)[source]

Try to write self as exp_polar(2*pi*I*n)*z in a nice way. Return (z, n).

>>> from sympy import exp_polar, I, pi
>>> from sympy.abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)


If allow_half is True, also extract exp_polar(I*pi):

>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)

extract_multiplicatively(c)[source]

Return None if it’s not possible to make self in the form c * something in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols, Rational

>>> x, y = symbols('x,y', real=True)

>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2

>>> ((x*y)**3).extract_multiplicatively(x**4 * y)

>>> (2*x).extract_multiplicatively(2)
x

>>> (2*x).extract_multiplicatively(3)

>>> (Rational(1,2)*x).extract_multiplicatively(3)
x/6

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

See the factor() function in sympy.polys.polytools

getO()[source]

Returns the additive O(..) symbol if there is one, else None.

getn()[source]

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Examples

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()

integrate(*args, **kwargs)[source]

See the integrate function in sympy.integrals

invert(g)[source]

See the invert function in sympy.polys

is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, two strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x:pi, a:2}) == eq.subs({x:pi, a:3}) == 0
True

>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() # could be 0 or 1
False

is_number[source]

Returns True if ‘self’ is a number.

>>> from sympy import log, Integral
>>> from sympy.abc import x, y

>>> x.is_number
False
>>> (2*x).is_number
False
>>> (2 + log(2)).is_number
True
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True

is_polynomial(*syms)[source]

Return True if self is a polynomial in syms and False otherwise.

This checks if self is an exact polynomial in syms. This function returns False for expressions that are “polynomials” with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, *syms) should work only if and only if expr.is_polynomial(*syms) returns True. The polynomial does not have to be in expanded form. If no symbols are given, all free symbols in the expression will be used.

This is not part of the assumptions system. You cannot do Symbol(‘z’, polynomial=True).

Examples

>>> from sympy import Symbol
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False

>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False


This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a polynomial to become one.

>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True

>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True


is_rational_function(*syms)[source]

Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.

This function returns False for expressions that are “rational functions” with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True.

This is not part of the assumptions system. You cannot do Symbol(‘z’, rational_function=True).

Examples

>>> from sympy import Symbol, sin
>>> from sympy.abc import x, y

>>> (x/y).is_rational_function()
True

>>> (x**2).is_rational_function()
True

>>> (x/sin(y)).is_rational_function(y)
False

>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False


This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one.

>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True


Returns the leading term a*x**b as a tuple (a, b).

Examples

>>> from sympy.abc import x
(1, 0)
(1, -2)

limit(x, xlim, dir='+')[source]

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')[source]

Wrapper for series yielding an iterator of the terms of the series.

Note: an infinite series will yield an infinite iterator. The following, for exaxmple, will never terminate. It will just keep printing terms of the sin(x) series:

for term in sin(x).lseries(x):
print term


The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you don’t know how many you should ask for in nseries() using the “n” parameter.

nseries(x=None, x0=0, n=6, dir='+', logx=None)[source]

Wrapper to _eval_nseries if assumptions allow, else to series.

If x is given, x0 is 0, dir=’+’, and self has x, then _eval_nseries is called. This calculates “n” terms in the innermost expressions and then builds up the final series just by “cross-multiplying” everything out.

Advantage – it’s fast, because we don’t have to determine how many terms we need to calculate in advance.

Disadvantage – you may end up with less terms than you may have expected, but the O(x**n) term appended will always be correct and so the result, though perhaps shorter, will also be correct.

If any of those assumptions is not met, this is treated like a wrapper to series which will try harder to return the correct number of terms.

nsimplify(constants=[], tolerance=None, full=False)[source]

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')[source]

See the powsimp function in sympy.simplify

primitive()[source]

Return the positive Rational that can be extracted non-recursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float).

Examples

>>> from sympy.abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True


See the radsimp function in sympy.simplify

ratsimp()[source]

See the ratsimp function in sympy.simplify

refine(assumption=True)[source]

See the refine function in sympy.assumptions

removeO()[source]

Removes the additive O(..) symbol if there is one

round(p=0)[source]

Return x rounded to the given decimal place.

If a complex number would results, apply round to the real and imaginary components of the number.

Notes

Do not confuse the Python builtin function, round, with the SymPy method of the same name. The former always returns a float (or raises an error if applied to a complex value) while the latter returns either a Number or a complex number:

>>> isinstance(round(S(123), -2), Number)
False
>>> isinstance(S(123).round(-2), Number)
True
>>> isinstance((3*I).round(), Mul)
True
True


Examples

>>> from sympy import pi, E, I, S, Add, Mul, Number
>>> S(10.5).round()
11.
>>> pi.round()
3.
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6. + 3.*I


The round method has a chopping effect:

>>> (2*pi + I/10).round()
6.
>>> (pi/10 + 2*I).round()
2.*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I

separate(deep=False, force=False)[source]

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')[source]

Series expansion of “self” around x = x0 yielding either terms of the series one by one (the lazy series given when n=None), else all the terms at once when n != None.

Note: when n != None, if an O() term is returned then the x in the in it and the entire expression represents x - x0, the displacement from x0. (If there is no O() term then the series was exact and x has it’s normal meaning.) This is currently necessary since sympy’s O() can only represent terms at x0=0. So instead of:

cos(x).series(x0=1, n=2) --> (1 - x)*sin(1) + cos(1) + O((x - 1)**2)

which graphically looks like this:

   |
.|.         . .
. | \      .     .
---+----------------------
|   . .          . .
|                  x=0

-x*sin(1) + cos(1) + O(x**2)


whose graph is this:

   \ |
. .|        . .
.   \      .     .
-----+\------------------.
| . .          . .
|                  x=0

which is identical to cos(x + 1).series(n=2).

Usage:

Returns the series expansion of “self” around the point x = x0 with respect to x up to O(x**n) (default n is 6).

If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.

>>> from sympy import cos, exp
>>> from sympy.abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)


If n=None then an iterator of the series terms will be returned.

>>> term=cos(x).series(n=None)
>>> [term.next() for i in range(2)]
[1, -x**2/2]


For dir=+ (default) the series is calculated from the right and for dir=- the series from the left. For smooth functions this flag will not alter the results.

>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x

simplify()[source]

See the simplify function in sympy.simplify

together(*args, **kwargs)[source]

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)[source]

See the trigsimp function in sympy.simplify

## AtomicExpr¶

class sympy.core.expr.AtomicExpr[source]

A parent class for object which are both atoms and Exprs.

For example: Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ...

## symbol¶

### Symbol¶

class sympy.core.symbol.Symbol[source]
Assumptions:
commutative = True

You can override the default assumptions in the constructor:

>>> from sympy import symbols
>>> A,B = symbols('A,B', commutative = False)
>>> bool(A*B != B*A)
True
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
True


### Wild¶

class sympy.core.symbol.Wild[source]

Wild() matches any expression but another Wild().

### Dummy¶

class sympy.core.symbol.Dummy[source]

Dummy symbols are each unique, identified by an internal count index:

>>> from sympy import Dummy
>>> bool(Dummy("x") == Dummy("x")) == True
False


If a name is not supplied then a string value of the count index will be used. This is useful when a temporary variable is needed and the name of the variable used in the expression is not important.

>>> Dummy._count = 0 # /!\ this should generally not be changed; it is being
>>> Dummy()          # used here to make sure that the doctest passes.
_0


### symbols¶

sympy.core.symbol.symbols(names, **args)[source]

Transform strings into instances of Symbol class.

symbols() function returns a sequence of symbols with names taken from names argument, which can be a comma or whitespace delimited string, or a sequence of strings:

>>> from sympy import symbols, Function

>>> x, y, z = symbols('x,y,z')
>>> a, b, c = symbols('a b c')


The type of output is dependent on the properties of input arguments:

>>> symbols('x')
x
>>> symbols('x,')
(x,)
>>> symbols('x,y')
(x, y)
>>> symbols(('a', 'b', 'c'))
(a, b, c)
>>> symbols(['a', 'b', 'c'])
[a, b, c]
>>> symbols(set(['a', 'b', 'c']))
set([a, b, c])


If an iterable container is needed for a single symbol, set the seq argument to True or terminate the symbol name with a comma:

>>> symbols('x', seq=True)
(x,)


To reduce typing, range syntax is supported to create indexed symbols:

>>> symbols('x:10')
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)

>>> symbols('x5:10')
(x5, x6, x7, x8, x9)

>>> symbols('x5:10,y:5')
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)

>>> symbols(('x5:10', 'y:5'))
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))


To reduce typing even more, lexicographic range syntax is supported:

>>> symbols('x:z')
(x, y, z)

>>> symbols('a:d,x:z')
(a, b, c, d, x, y, z)

>>> symbols(('a:d', 'x:z'))
((a, b, c, d), (x, y, z))


All newly created symbols have assumptions set accordingly to args:

>>> a = symbols('a', integer=True)
>>> a.is_integer
True

>>> x, y, z = symbols('x,y,z', real=True)
>>> x.is_real and y.is_real and z.is_real
True


Despite its name, symbols() can create symbol–like objects of other type, for example instances of Function or Wild classes. To achieve this, set cls keyword argument to the desired type:

>>> symbols('f,g,h', cls=Function)
(f, g, h)

>>> type(_[0])
<class 'sympy.core.function.UndefinedFunction'>


### var¶

sympy.core.symbol.var(names, **args)[source]

Create symbols and inject them into the global namespace.

This calls symbols() with the same arguments and puts the results into the global namespace. It’s recommended not to use var() in library code, where symbols() has to be used:

>>> from sympy import var

>>> var('x')
x
>>> x
x

>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc

>>> var('x,y', real=True)
(x, y)
>>> x.is_real and y.is_real
True


See symbol() documentation for more details on what kinds of arguments can be passed to var().

## numbers¶

### Number¶

class sympy.core.numbers.Number[source]

Represents any kind of number in sympy.

Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class.

If you want to represent, for example, 1+sqrt(2), then you need to do:

Rational(1) + sqrt(Rational(2))


Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

cofactors(other)[source]

Compute GCD and cofactors of input arguments.

gcd(other)[source]

Compute greatest common divisor of input arguments.

lcm(other)[source]

Compute least common multiple of input arguments.

### Float¶

class sympy.core.numbers.Float[source]

Represents a floating point number. It is capable of representing arbitrary-precision floating-point numbers.

Notes

Floats are inexact by their nature unless their value is a binary-exact value.

>>> approx, exact = Float(.1, 1), Float(.125, 1)


For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision:

>>> approx.evalf(5)
0.099609


By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy:

>>> Float(exact, 5)
0.12500
>>> exact.evalf(20)
0.12500000000000000000


Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the underlying float (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros:

>>> Float(0.3, 20)
0.29999999999999998890


If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python’s float is used:

>>> Float('0.3', 20)
0.30000000000000000000


Although you can increase the precision of an existing Float using Float it will not increase the accuracy – the underlying value is not changed:

>>> def show(f): # binary rep of Float
...     from sympy import Mul, Pow
...     s, m, e, b = f._mpf_
...     v = Mul(m, Pow(2, e, evaluate=False), evaluate=False)
...     print '%s at prec=%s' % (v, f._prec)
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10


The same thing happens when evalf is used on a Float:

>>> show(t.evalf(20))
4915/2**14 at prec=70
>>> show(t.evalf(2))
307/2**10 at prec=10


Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p:

>>> n, c, p = 1, 5, 0
>>> (-1)**n*c*2**p
-5
>>> Float((1, 5, 0))
-5.00000000000000


An actual mpf tuple also contains the number of bits in c as the last element of the tuple, but this is not needed for instantiation:

>>> _._mpf_
(1, 5, 0, 3)


Examples

>>> from sympy import Float
>>> Float(3.5) # convert from Python float or int
3.50000000000000
>>> Float(3) # reverts to Integer
3
>>> Float(3, '') # forced to Float
3.


Floats can be created from a string representations of Python floats to force ints to Float or to enter high-precision (> 15 significant digits) values:

>>> Float('.0010')
0.00100000000000000
>>> Float('1e-3')
0.00100000000000000
>>> Float('1e-3', 3)
0.00100


Float can automatically count significant figures if a null string is sent for the precision; space are also allowed in the string. (Auto- counting is only allowed for strings, ints and longs).

>>> Float('123 456 789 . 123 456', '')
123456789.123456
>>> Float('12e-3', '')
0.012


### Rational¶

class sympy.core.numbers.Rational[source]

Represents integers and rational numbers (p/q) of any size.

Examples

>>> from sympy import Rational
>>> from sympy.abc import x, y
>>> Rational(3)
3
>>> Rational(1,2)
1/2
>>> Rational(1.5)
1


Rational can also accept strings that are valid literals for reals:

>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10


Parsing needs for any other type of string for which a Rational is desired can be handled with the rational=True option in sympify() which produces rationals from strings like ‘.[3]’ (=1/3) and ‘3/10’ (=3/10).

Low-level

Access numerator and denominator as .p and .q:

>>> r = Rational(3,4)
>>> r
3/4
>>> r.p
3
>>> r.q
4


Note that p and q return integers (not sympy Integers) so some care is needed when using them in expressions:

>>> r.p//r.q
0


Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from sympy import S
>>> (S(-3)/2).as_content_primitive()
(3/2, -1)


See docstring of Expr.as_content_primitive for more examples.

cofactors(other)[source]

Compute GCD and cofactors of input arguments.

factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False)[source]

A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used.

gcd(other)[source]

Compute greatest common divisor of input arguments.

lcm(other)[source]

Compute least common multiple of input arguments.

limit_denominator(max_denominator=1000000)[source]

Closest Rational to self with denominator at most max_denominator.

>>> from sympy import Rational
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99


### Integer¶

class sympy.core.numbers.Integer[source]
factorial()[source]

Compute factorial of $$self$$.

gcdex(other)[source]

Extended Euclidean Algorithm.

half_gcdex(other)[source]

Half Extended Euclidean Algorithm.

invert(other)[source]

Invert $$self$$ modulo $$other$$, if possible.

isqrt()[source]

Compute integer square root of $$self$$.

### NumberSymbol¶

class sympy.core.numbers.NumberSymbol[source]
approximation(number_cls)[source]

Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None.

### RealNumber¶

sympy.core.numbers.RealNumber

alias of Float

### Real¶

class sympy.core.numbers.Real[source]

Deprecated alias for the Float constructor.

### igcd¶

sympy.core.numbers.igcd(a, b)[source]

Computes positive, integer greatest common divisor of two numbers.

The algorithm is based on the well known Euclid’s algorithm. To improve speed, igcd() has its own caching mechanism implemented.

### ilcm¶

sympy.core.numbers.ilcm(a, b)[source]

Computes integer least common multiple of two numbers.

### seterr¶

sympy.core.numbers.seterr(divide=False)[source]

Should sympy raise an exception on 0/0 or return a nan?

divide == True .... raise an exception divide == False ... return nan

### E¶

sympy.core.numbers.E

### I¶

sympy.core.numbers.I

### nan¶

sympy.core.numbers.nan(cls)

Not a Number.

This represents the corresponding data type to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python float('nan').

NaN serves as a place holder for numeric values that are indeterminate, but not infinite. Most operations on nan, produce another nan. Most indeterminate forms, such as 0/0 or oo - oo produce nan.  Three exceptions are 0**0, 1**oo, and oo**0, which all produce 1 (this is consistent with Python’s float).

NaN is a singleton, and can be accessed by S.NaN, or can be imported as nan.

References

Examples

>>> from sympy import nan, S, oo
>>> nan is S.NaN
True
>>> oo - oo
nan
>>> nan + 1
nan


### oo¶

sympy.core.numbers.oo(cls)

### pi¶

sympy.core.numbers.pi(cls)

### zoo¶

sympy.core.numbers.zoo(cls)

## power¶

### Pow¶

class sympy.core.power.Pow[source]
as_base_exp()[source]

Return base and exp of self unless base is 1/Integer, then return Integer, -exp.

If this extra processing is not needed, the base and exp properties will give the raw arguments, e.g. (1/2, 2) for (1/2)**2 rather than (2, -2).

Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from sympy import sqrt
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
(2, sqrt(1 + sqrt(2)))
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
(1, sqrt(3)*sqrt(1 + sqrt(2)))

>>> from sympy import expand_power_base, powsimp, Mul
>>> from sympy.abc import x, y

>>> ((2*x + 2)**2).as_content_primitive()
(4, (x + 1)**2)
>>> (4**((1 + y)/2)).as_content_primitive()
(2, 4**(y/2))
>>> (3**((1 + y)/2)).as_content_primitive()
(1, 3**((y + 1)/2))
>>> (3**((5 + y)/2)).as_content_primitive()
(9, 3**((y + 1)/2))
>>> eq = 3**(2 + 2*x)
>>> powsimp(eq) == eq
True
>>> eq.as_content_primitive()
(9, 3**(2*x))
>>> powsimp(Mul(*_))
9**(x + 1)

>>> eq = (2 + 2*x)**y
>>> s = expand_power_base(eq); s.is_Mul, s
(False, (2*x + 2)**y)
>>> eq.as_content_primitive()
(1, (2*(x + 1))**y)
>>> s = expand_power_base(_[1]); s.is_Mul, s
(True, 2**y*(x + 1)**y)


See docstring of Expr.as_content_primitive for more examples.

### integer_nthroot¶

sympy.core.power.integer_nthroot(y, n)[source]

Return a tuple containing x = floor(y**(1/n)) and a boolean indicating whether the result is exact (that is, whether x**n == y).

>>> from sympy import integer_nthroot
>>> integer_nthroot(16,2)
(4, True)
>>> integer_nthroot(26,2)
(5, False)


## mul¶

### Mul¶

class sympy.core.mul.Mul[source]
as_coeff_Mul(rational=False)[source]

Efficiently extract the coefficient of a product.

Return the tuple (R, self/R) where R is the positive Rational extracted from self.

Examples

>>> from sympy import sqrt
>>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
(6, -sqrt(2)*(-sqrt(2) + 1))


See docstring of Expr.as_content_primitive for more examples.

as_ordered_factors(order=None)[source]

Transform an expression into an ordered list of factors.

Examples

>>> from sympy import sin, cos
>>> from sympy.abc import x, y

>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
[2, x, y, sin(x), cos(x)]

as_two_terms(*args, **kw_args)[source]

Return head and tail of self.

This is the most efficient way to get the head and tail of an expression.

• if you want only the head, use self.args[0];
• if you want to process the arguments of the tail then use self.as_coef_mul() which gives the head and a tuple containing the arguments of the tail when treated as a Mul.
• if you want the coefficient when self is treated as an Add then use self.as_coeff_add()[0]
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)

classmethod flatten(seq)[source]

Return commutative, noncommutative and order arguments by combining related terms.

Notes

• In an expression like a*b*c, python process this through sympy as Mul(Mul(a, b), c). This can have undesirable consequences.

>>> from sympy import Mul, sqrt
>>> from sympy.abc import x, y, z
>>> 2*(x + 1) # this is the 2-arg Mul behavior
2*x + 2
>>> y*(x + 1)*2
2*y*(x + 1)
>>> 2*(x + 1)*y # 2-arg result will be obtained first
y*(2*x + 2)
>>> Mul(2, x + 1, y) # all 3 args simultaneously processed
2*y*(x + 1)
>>> 2*((x + 1)*y) # parentheses can control this behavior
2*y*(x + 1)


Powers with compound bases may not find a single base to combine with unless all arguments are processed at once. Post-processing may be necessary in such cases. {c.f. http://code.google.com/p/sympy/issues/detail?id=2629}

>>> a = sqrt(x*sqrt(y))
>>> a**3
(x*sqrt(y))**(3/2)
>>> Mul(a,a,a)
(x*sqrt(y))**(3/2)
>>> a*a*a
x*sqrt(y)*sqrt(x*sqrt(y))
>>> _.subs(a.base, z).subs(z, a.base)
(x*sqrt(y))**(3/2)

• If more than two terms are being multiplied then all the previous terms will be re-processed for each new argument. So if each of a, b and c were Mul expression, then a*b*c (or building up the product with *=) will process all the arguments of a and b twice: once when a*b is computed and again when c is multiplied.

Using Mul(a, b, c) will process all arguments once.

• The results of Mul are cached according to arguments, so flatten will only be called once for Mul(a, b, c). If you can structure a calculation so the arguments are most likely to be repeats then this can save time in computing the answer. For example, say you had a Mul, M, that you wished to divide by d[i] and multiply by n[i] and you suspect there are many repeats in n. It would be better to compute M*n[i]/d[i] rather than M/d[i]*n[i] since every time n[i] is a repeat, the product, M*n[i] will be returned without flattening – the cached value will be returned. If you divide by the d[i] first (and those are more unique than the n[i]) then that will create a new Mul, M/d[i] the args of which will be traversed again when it is multiplied by n[i].

This consideration is moot if the cache is turned off.

Nb

The validity of the above notes depends on the implementation details of Mul and flatten which may change at any time. Therefore, you should only consider them when your code is highly performance sensitive.

Removal of 1 from the sequence is already handled by AssocOp.__new__.

### prod¶

sympy.core.mul.prod(a, start=1)[source]

Return product of elements of a. Start with int 1 so if only ints are included then an int result is returned.

Examples

>>> from sympy import prod, S
>>> prod(range(3))
0
>>> type(_) is int
True
>>> prod([S(2), 3])
6
>>> _.is_Integer
True


You can start the product at something other than 1: >>> prod([1, 2], 3) 6

Efficiently extract the coefficient of a summation.

Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms.

Examples

>>> from sympy.abc import x, y
(7, (3*x,))
(0, (7*x,))

as_coefficients_dict(a)[source]

Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0. If an expression is not an Add it is considered to have a single term.

Examples

>>> from sympy.abc import a, x
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}


Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression.

Examples

>>> from sympy import sqrt
>>> (3 + 3*sqrt(2)).as_content_primitive()
(3, 1 + sqrt(2))


Radical content can also be factored out of the primitive:

>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))


See docstring of Expr.as_content_primitive for more examples.

as_real_imag(deep=True, **hints)[source]

returns a tuple represeting a complex numbers

Examples

>>> from sympy import I
>>> (7 + 9*I).as_real_imag()
(7, 9)

as_two_terms(*args, **kw_args)[source]

Return head and tail of self.

This is the most efficient way to get the head and tail of an expression.

• if you want only the head, use self.args[0];
• if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add.
• if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0]
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)

classmethod class_key()[source]

Nice order of classes

Returns the leading term and it’s order.

Examples

>>> from sympy.abc import x
>>> (x + 1 + 1/x**5).extract_leading_order(x)
((x**(-5), O(x**(-5))),)
((1, O(1)),)
((x, O(x)),)

classmethod flatten(seq)[source]

Takes the sequence “seq” of nested Adds and returns a flatten list.

Returns: (commutative_part, noncommutative_part, order_symbols)

Applies associativity, all terms are commutable with respect to addition.

NB: the removal of 0 is already handled by AssocOp.__new__

matches(expr, repl_dict={})

Matches Add/Mul “pattern” to an expression “expr”.

repl_dict ... a dictionary of (wild: expression) pairs, that get
returned with the results

This function is the main workhorse for Add/Mul.

For instance:

>>> from sympy import symbols, Wild, sin
>>> a = Wild("a")
>>> b = Wild("b")
>>> c = Wild("c")
>>> x, y, z = symbols("x y z")
>>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
{a_: x, b_: y, c_: z}


In the example above, “a+sin(b)*c” is the pattern, and “x+sin(y)*z” is the expression.

The repl_dict contains parts that were already matched. For example here:

>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
{a_: x, b_: y, c_: z}


the only function of the repl_dict is to return it in the result, e.g. if you omit it:

>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
{b_: y, c_: z}


the “a: x” is not returned in the result, but otherwise it is equivalent.

primitive()[source]

Return (R, self/R) where R is the Rational GCD of self.

R is collected only from the leading coefficient of each term.

Examples

>>> from sympy.abc import x, y

>>> (2*x + 4*y).primitive()
(2, x + 2*y)

>>> (2*x/3 + 4*y/9).primitive()
(2/9, 3*x + 2*y)

>>> (2*x/3 + 4.2*y).primitive()
(1/3, 2*x + 12.6*y)


No subprocessing of term factors is performed:

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


Recursive subprocessing can be done with the as_content_primitive() method:

>>> ((2 + 2*x)*x + 2).as_content_primitive()
(2, x*(x + 1) + 1)


## mod¶

### Mod¶

class sympy.core.mod.Mod[source]

Represents a modulo operation on symbolic expressions.

Receives two arguments, dividend p and divisor q.

The convention used is the same as python’s: the remainder always has the same sign as the divisor.

Examples

>>> from sympy.abc import x, y
>>> x**2 % y
Mod(x**2, y)
>>> _.subs({x: 5, y: 6})
1


## relational¶

### Rel¶

class sympy.core.relational.Rel[source]

A handy wrapper around the Relational class. Rel(a,b, op)

Examples

>>> from sympy import Rel
>>> from sympy.abc import x, y
>>> Rel(y, x+x**2, '==')
y == x**2 + x


### Eq¶

class sympy.core.relational.Eq[source]

A handy wrapper around the Relational class. Eq(a,b)

Examples

>>> from sympy import Eq
>>> from sympy.abc import x, y
>>> Eq(y, x+x**2)
y == x**2 + x


### Ne¶

class sympy.core.relational.Ne[source]

A handy wrapper around the Relational class. Ne(a,b)

Examples

>>> from sympy import Ne
>>> from sympy.abc import x, y
>>> Ne(y, x+x**2)
y != x**2 + x


### Lt¶

class sympy.core.relational.Lt[source]

A handy wrapper around the Relational class. Lt(a,b)

Examples

>>> from sympy import Lt
>>> from sympy.abc import x, y
>>> Lt(y, x+x**2)
y < x**2 + x


### Le¶

class sympy.core.relational.Le[source]

A handy wrapper around the Relational class. Le(a,b)

Examples

>>> from sympy import Le
>>> from sympy.abc import x, y
>>> Le(y, x+x**2)
y <= x**2 + x


### Gt¶

class sympy.core.relational.Gt[source]

A handy wrapper around the Relational class. Gt(a,b)

Examples

>>> from sympy import Gt
>>> from sympy.abc import x, y
>>> Gt(y, x + x**2)
y > x**2 + x


### Ge¶

class sympy.core.relational.Ge[source]

A handy wrapper around the Relational class. Ge(a,b)

Examples

>>> from sympy import Ge
>>> from sympy.abc import x, y
>>> Ge(y, x + x**2)
y >= x**2 + x


### Equality¶

class sympy.core.relational.Equality[source]

### GreaterThan¶

class sympy.core.relational.GreaterThan[source]

Class representations of inequalities.

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name Symbol
GreaterThan (>=)
LessThan (<=)
StrictGreaterThan (>)
StrictLessThan (<)

All classes take two arguments, lhs and rhs.

Signature Example Math equivalent
GreaterThan(lhs, rhs) lhs >= rhs
LessThan(lhs, rhs) lhs <= rhs
StrictGreaterThan(lhs, rhs) lhs > rhs
StrictLessThan(lhs, rhs) lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from sympy import GreaterThan, StrictGreaterThan
>>> from sympy import LessThan,    StrictLessThan
>>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
>>> from sympy.abc import x, y, z
>>> from sympy.core.relational import Relational

>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'


Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1


If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x


The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z  # silent error!  Where did x go?
>>> e
y < z


Due to an implementation detail or decision of Python [R13], there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
And(x < y, y < z)


Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [R14]):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z


Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

 [R13] This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see http://docs.python.org/reference/expressions.html#notin). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example, 1 > 2 > 3 is evaluated by Python as (1 > 2) and (2 > 3). The and operator coerces each side into a bool, returning the object itself when it short-circuits. Currently, the bool of the –Than operators will give True or False arbitrarily. Thus, if we were to compute x > y > z, with x, y, and z being Symbols, Python converts the statement (roughly) into these steps: x > y > z (x > y) and (y > z) (GreaterThanObject) and (y > z) (GreaterThanObject.__nonzero__()) and (y > z) (True) and (y > z) (y > z) LessThanObject Because of the “and” added at step 2, the statement gets turned into a weak ternary statement. If the first object evalutes __nonzero__ as True, then the second object, (y > z) is returned. If the first object evaluates __nonzero__ as False (step 5), then (x > y) is returned. In Python, there is no way to override the and operator, or to control how it short circuits, so it is impossible to make something like x > y > z work. There is an open PEP to change this, PEP 335, but until that is implemented, this cannot be made to work.
 [R14] For more information, see these two bug reports: “Separate boolean and symbolic relationals” Issue 1887 “It right 0 < x < 1 ?” Issue 2960

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print e1
x >= 2

>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print '%s\n%s\n%s\n%s' % rels
x >= 2
x > 2
x <= 2
x < 2


Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print e2
x >= 2
>>> print "e1: %s,    e2: %s" % (e1, e2)
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True


However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x >= 1
x >= 1
x >= 1

>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x > 1
x > 1
x > 1

>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print "%s\n%s\n%s" % rels
x <= 1
x <= 1
x <= 1

>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x < 1
x < 1
x < 1


### LessThan¶

class sympy.core.relational.LessThan[source]

Class representations of inequalities.

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name Symbol
GreaterThan (>=)
LessThan (<=)
StrictGreaterThan (>)
StrictLessThan (<)

All classes take two arguments, lhs and rhs.

Signature Example Math equivalent
GreaterThan(lhs, rhs) lhs >= rhs
LessThan(lhs, rhs) lhs <= rhs
StrictGreaterThan(lhs, rhs) lhs > rhs
StrictLessThan(lhs, rhs) lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from sympy import GreaterThan, StrictGreaterThan
>>> from sympy import LessThan,    StrictLessThan
>>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
>>> from sympy.abc import x, y, z
>>> from sympy.core.relational import Relational

>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'


Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1


If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x


The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z  # silent error!  Where did x go?
>>> e
y < z


Due to an implementation detail or decision of Python [R15], there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
And(x < y, y < z)


Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [R16]):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z


Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

 [R15] This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see http://docs.python.org/reference/expressions.html#notin). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example, 1 > 2 > 3 is evaluated by Python as (1 > 2) and (2 > 3). The and operator coerces each side into a bool, returning the object itself when it short-circuits. Currently, the bool of the –Than operators will give True or False arbitrarily. Thus, if we were to compute x > y > z, with x, y, and z being Symbols, Python converts the statement (roughly) into these steps: x > y > z (x > y) and (y > z) (GreaterThanObject) and (y > z) (GreaterThanObject.__nonzero__()) and (y > z) (True) and (y > z) (y > z) LessThanObject Because of the “and” added at step 2, the statement gets turned into a weak ternary statement. If the first object evalutes __nonzero__ as True, then the second object, (y > z) is returned. If the first object evaluates __nonzero__ as False (step 5), then (x > y) is returned. In Python, there is no way to override the and operator, or to control how it short circuits, so it is impossible to make something like x > y > z work. There is an open PEP to change this, PEP 335, but until that is implemented, this cannot be made to work.
 [R16] For more information, see these two bug reports: “Separate boolean and symbolic relationals” Issue 1887 “It right 0 < x < 1 ?” Issue 2960

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print e1
x >= 2

>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print '%s\n%s\n%s\n%s' % rels
x >= 2
x > 2
x <= 2
x < 2


Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print e2
x >= 2
>>> print "e1: %s,    e2: %s" % (e1, e2)
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True


However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x >= 1
x >= 1
x >= 1

>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x > 1
x > 1
x > 1

>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print "%s\n%s\n%s" % rels
x <= 1
x <= 1
x <= 1

>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x < 1
x < 1
x < 1


### Unequality¶

class sympy.core.relational.Unequality[source]

### StrictGreaterThan¶

class sympy.core.relational.StrictGreaterThan[source]

Class representations of inequalities.

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name Symbol
GreaterThan (>=)
LessThan (<=)
StrictGreaterThan (>)
StrictLessThan (<)

All classes take two arguments, lhs and rhs.

Signature Example Math equivalent
GreaterThan(lhs, rhs) lhs >= rhs
LessThan(lhs, rhs) lhs <= rhs
StrictGreaterThan(lhs, rhs) lhs > rhs
StrictLessThan(lhs, rhs) lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from sympy import GreaterThan, StrictGreaterThan
>>> from sympy import LessThan,    StrictLessThan
>>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
>>> from sympy.abc import x, y, z
>>> from sympy.core.relational import Relational

>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'


Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1


If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x


The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z  # silent error!  Where did x go?
>>> e
y < z


Due to an implementation detail or decision of Python [R17], there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
And(x < y, y < z)


Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [R18]):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z


Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

 [R17] This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see http://docs.python.org/reference/expressions.html#notin). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example, 1 > 2 > 3 is evaluated by Python as (1 > 2) and (2 > 3). The and operator coerces each side into a bool, returning the object itself when it short-circuits. Currently, the bool of the –Than operators will give True or False arbitrarily. Thus, if we were to compute x > y > z, with x, y, and z being Symbols, Python converts the statement (roughly) into these steps: x > y > z (x > y) and (y > z) (GreaterThanObject) and (y > z) (GreaterThanObject.__nonzero__()) and (y > z) (True) and (y > z) (y > z) LessThanObject Because of the “and” added at step 2, the statement gets turned into a weak ternary statement. If the first object evalutes __nonzero__ as True, then the second object, (y > z) is returned. If the first object evaluates __nonzero__ as False (step 5), then (x > y) is returned. In Python, there is no way to override the and operator, or to control how it short circuits, so it is impossible to make something like x > y > z work. There is an open PEP to change this, PEP 335, but until that is implemented, this cannot be made to work.
 [R18] For more information, see these two bug reports: “Separate boolean and symbolic relationals” Issue 1887 “It right 0 < x < 1 ?” Issue 2960

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print e1
x >= 2

>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print '%s\n%s\n%s\n%s' % rels
x >= 2
x > 2
x <= 2
x < 2


Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print e2
x >= 2
>>> print "e1: %s,    e2: %s" % (e1, e2)
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True


However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x >= 1
x >= 1
x >= 1

>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x > 1
x > 1
x > 1

>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print "%s\n%s\n%s" % rels
x <= 1
x <= 1
x <= 1

>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x < 1
x < 1
x < 1


### StrictLessThan¶

class sympy.core.relational.StrictLessThan[source]

Class representations of inequalities.

The *Than classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:

lhs >= rhs

In total, there are four *Than classes, to represent the four inequalities:

Class Name Symbol
GreaterThan (>=)
LessThan (<=)
StrictGreaterThan (>)
StrictLessThan (<)

All classes take two arguments, lhs and rhs.

Signature Example Math equivalent
GreaterThan(lhs, rhs) lhs >= rhs
LessThan(lhs, rhs) lhs <= rhs
StrictGreaterThan(lhs, rhs) lhs > rhs
StrictLessThan(lhs, rhs) lhs < rhs

In addition to the normal .lhs and .rhs of Relations, *Than inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:

>>> from sympy import GreaterThan, StrictGreaterThan
>>> from sympy import LessThan,    StrictLessThan
>>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
>>> from sympy.abc import x, y, z
>>> from sympy.core.relational import Relational

>>> e = GreaterThan(x, 1)
>>> e
x >= 1
>>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
'x >= 1 is the same as 1 <= x'


Notes

There are a couple of “gotchas” when using Python’s operators.

The first enters the mix when comparing against a literal number as the lhs argument. Due to the order that Python decides to parse a statement, it may not immediately find two objects comparable. For example, to evaluate the statement (1 < x), Python will first recognize the number 1 as a native number, and then that x is not a native number. At this point, because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation, (x > 1). Unfortunately, there is no way available to SymPy to recognize this has happened, so the statement (1 < x) will turn silently into (x > 1).

>>> e1 = x >  1
>>> e2 = x >= 1
>>> e3 = x <  1
>>> e4 = x <= 1
>>> e5 = 1 >  x
>>> e6 = 1 >= x
>>> e7 = 1 <  x
>>> e8 = 1 <= x
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
x > 1     x >= 1
x < 1     x <= 1
x < 1     x <= 1
x > 1     x >= 1


If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways: (1) “sympify” the literal before comparison, (2) use one of the wrappers, or (3) use the less succinct methods described above:

>>> e1 = S(1) >  x
>>> e2 = S(1) >= x
>>> e3 = S(1) <  x
>>> e4 = S(1) <= x
>>> e5 = Gt(1, x)
>>> e6 = Ge(1, x)
>>> e7 = Lt(1, x)
>>> e8 = Le(1, x)
>>> print "%s     %s\n"*4 % (e1, e2, e3, e4, e5, e6, e7, e8)
1 > x     1 >= x
1 < x     1 <= x
1 > x     1 >= x
1 < x     1 <= x


The other gotcha is with chained inequalities. Occasionally, one may be tempted to write statements like:

>>> e = x < y < z  # silent error!  Where did x go?
>>> e
y < z


Due to an implementation detail or decision of Python [R19], there is no way for SymPy to reliably create that as a chained inequality. To create a chained inequality, the only method currently available is to make use of And:

>>> e = And(x < y, y < z)
>>> type( e )
And
>>> e
And(x < y, y < z)


Note that this is different than chaining an equality directly via use of parenthesis (this is currently an open bug in SymPy [R20]):

>>> e = (x < y) < z
>>> type( e )
<class 'sympy.core.relational.StrictLessThan'>
>>> e
(x < y) < z


Any code that explicitly relies on this latter functionality will not be robust as this behaviour is completely wrong and will be corrected at some point. For the time being (circa Jan 2012), use And to create chained inequalities.

 [R19] This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see http://docs.python.org/reference/expressions.html#notin). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example, 1 > 2 > 3 is evaluated by Python as (1 > 2) and (2 > 3). The and operator coerces each side into a bool, returning the object itself when it short-circuits. Currently, the bool of the –Than operators will give True or False arbitrarily. Thus, if we were to compute x > y > z, with x, y, and z being Symbols, Python converts the statement (roughly) into these steps: x > y > z (x > y) and (y > z) (GreaterThanObject) and (y > z) (GreaterThanObject.__nonzero__()) and (y > z) (True) and (y > z) (y > z) LessThanObject Because of the “and” added at step 2, the statement gets turned into a weak ternary statement. If the first object evalutes __nonzero__ as True, then the second object, (y > z) is returned. If the first object evaluates __nonzero__ as False (step 5), then (x > y) is returned. In Python, there is no way to override the and operator, or to control how it short circuits, so it is impossible to make something like x > y > z work. There is an open PEP to change this, PEP 335, but until that is implemented, this cannot be made to work.
 [R20] For more information, see these two bug reports: “Separate boolean and symbolic relationals” Issue 1887 “It right 0 < x < 1 ?” Issue 2960

Examples

One generally does not instantiate these classes directly, but uses various convenience methods:

>>> e1 = Ge( x, 2 )      # Ge is a convenience wrapper
>>> print e1
x >= 2

>>> rels = Ge( x, 2 ), Gt( x, 2 ), Le( x, 2 ), Lt( x, 2 )
>>> print '%s\n%s\n%s\n%s' % rels
x >= 2
x > 2
x <= 2
x < 2


Another option is to use the Python inequality operators (>=, >, <=, <) directly. Their main advantage over the Ge, Gt, Le, and Lt counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).

>>> e2 = x >= 2
>>> print e2
x >= 2
>>> print "e1: %s,    e2: %s" % (e1, e2)
e1: x >= 2,    e2: x >= 2
>>> e1 == e2
True


However, it is also perfectly valid to instantiate a *Than class less succinctly and less conveniently:

>>> rels = Rel(x, 1, '>='), Relational(x, 1, '>='), GreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x >= 1
x >= 1
x >= 1

>>> rels = Rel(x, 1, '>'), Relational(x, 1, '>'), StrictGreaterThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x > 1
x > 1
x > 1

>>> rels = Rel(x, 1, '<='), Relational(x, 1, '<='), LessThan(x, 1)
>>> print "%s\n%s\n%s" % rels
x <= 1
x <= 1
x <= 1

>>> rels = Rel(x, 1, '<'), Relational(x, 1, '<'), StrictLessThan(x, 1)
>>> print '%s\n%s\n%s' % rels
x < 1
x < 1
x < 1


## multidimensional¶

### vectorize¶

class sympy.core.multidimensional.vectorize(*mdargs)[source]

Generalizes a function taking scalars to accept multidimensional arguments.

For example:

(1) @vectorize(0)
def sin(x):
....

sin([1, x, y])
--> [sin(1), sin(x), sin(y)]

(2) @vectorize(0,1)
def diff(f(y), y)
....

diff([f(x,y,z),g(x,y,z),h(x,y,z)], [x,y,z])
--> [[d/dx f, d/dy f, d/dz f], [d/dx g, d/dy g, d/dz g], [d/dx h, d/dy h, d/dz h]]

## function¶

### Lambda¶

class sympy.core.function.Lambda[source]

Lambda(x, expr) represents a lambda function similar to Python’s ‘lambda x: expr’. A function of several variables is written as Lambda((x, y, ...), expr).

A simple example:

>>> from sympy import Lambda
>>> from sympy.abc import x
>>> f = Lambda(x, x**2)
>>> f(4)
16


For multivariate functions, use:

>>> from sympy.abc import y, z, t
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
>>> f2(1, 2, 3, 4)
73


A handy shortcut for lots of arguments:

>>> p = x, y, z
>>> f = Lambda(p, x + y*z)
>>> f(*p)
x + y*z

expr[source]

The return value of the function

is_identity[source]

Return True if this Lambda is an identity function.

nargs[source]

The number of arguments that this function takes

variables[source]

The variables used in the internal representation of the function

### WildFunction¶

class sympy.core.function.WildFunction[source]

WildFunction() matches any expression but another WildFunction() XXX is this as intended, does it work ?

### Derivative¶

class sympy.core.function.Derivative[source]

Carries out differentiation of the given expression with respect to symbols.

expr must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the non-trivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative.

Ordering of variables:

If evaluate is set to True and the expression can not be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked. This sorting assumes that derivatives wrt Symbols commute, derivatives wrt non-Symbols commute, but Symbol and non-Symbol derivatives don’t commute with each other.

Derivative wrt non-Symbols:

This class also allows derivatives wrt non-Symbols that have _diff_wrt set to True, such as Function and Derivative. When a derivative wrt a non- Symbol is attempted, the non-Symbol is temporarily converted to a Symbol while the differentiation is performed.

Note that this may seem strange, that Derivative allows things like f(g(x)).diff(g(x)), or even f(cos(x)).diff(cos(x)). The motivation for allowing this syntax is to make it easier to work with variational calculus (i.e., the Euler-Lagrange method). The best way to understand this is that the action of derivative with respect to a non-Symbol is defined by the above description: the object is substituted for a Symbol and the derivative is taken with respect to that. This action is only allowed for objects for which this can be done unambiguously, for example Function and Derivative objects. Note that this leads to what may appear to be mathematically inconsistent results. For example:

>>> from sympy import cos, sin, sqrt
>>> from sympy.abc import x
>>> (2*cos(x)).diff(cos(x))
2
>>> (2*sqrt(1 - sin(x)**2)).diff(cos(x))
0


This appears wrong because in fact 2*cos(x) and 2*sqrt(1 - sin(x)**2) are identically equal. However this is the wrong way to think of this. Think of it instead as if we have something like this:

>>> from sympy.abc import c, s
>>> def F(u):
...     return 2*u
...
>>> def G(u):
...     return 2*sqrt(1 - u**2)
...
>>> F(cos(x))
2*cos(x)
>>> G(sin(x))
2*sqrt(-sin(x)**2 + 1)
>>> F(c).diff(c)
2
>>> F(c).diff(c)
2
>>> G(s).diff(c)
0
>>> G(sin(x)).diff(cos(x))
0


Here, the Symbols c and s act just like the functions cos(x) and sin(x), respectively. Think of 2*cos(x) as f(c).subs(c, cos(x)) (or f(c) at c = cos(x)) and 2*sqrt(1 - sin(x)**2) as g(s).subs(s, sin(x)) (or g(s) at s = sin(x)), where f(u) == 2*u and g(u) == 2*sqrt(1 - u**2). Here, we define the function first and evaluate it at the function, but we can actually unambiguously do this in reverse in SymPy, because expr.subs(Function, Symbol) is well-defined: just structurally replace the function everywhere it appears in the expression.

This is actually the same notational convenience used in the Euler-Lagrange method when one says F(t, f(t), f’(t)).diff(f(t)). What is actually meant is that the expression in question is represented by some F(t, u, v) at u = f(t) and v = f’(t), and F(t, f(t), f’(t)).diff(f(t)) simply means F(t, u, v).diff(u) at u = f(t).

We do not allow to take derivative with respect to expressions where this is not so well defined. For example, we do not allow expr.diff(x*y) because there are multiple ways of structurally defining where x*y appears in an expression, some of which may surprise the reader (for example, a very strict definition would have that (x*y*z).diff(x*y) == 0).

>>> from sympy.abc import x, y, z
>>> (x*y*z).diff(x*y)
Traceback (most recent call last):
...
ValueError: Can't differentiate wrt the variable: x*y, 1


Note that this definition also fits in nicely with the definition of the chain rule. Note how the chain rule in SymPy is defined using unevaluated Subs objects:

>>> from sympy import symbols, Function
>>> f, g = symbols('f g', cls=Function)
>>> f(2*g(x)).diff(x)
2*Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1,), (2*g(x),))
>>> f(g(x)).diff(x)
Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1,), (g(x),))


Finally, note that, to be consistent with variational calculus, and to ensure that the definition of substituting a Function for a Symbol in an expression is well-defined, derivatives of functions are assumed to not be related to the function. In other words, we have:

>>> from sympy import diff
>>> diff(f(x), x).diff(f(x))
0


The same is actually true for derivatives of different orders:

>>> diff(f(x), x, 2).diff(diff(f(x), x, 1))
0
>>> diff(f(x), x, 1).diff(diff(f(x), x, 2))
0


Note, any class can allow derivatives to be taken with respect to itself. See the docstring of Expr._diff_wrt.

Examples

Some basic examples:

>>> from sympy import Derivative, Symbol, Function
>>> f = Function('f')
>>> g = Function('g')
>>> x = Symbol('x')
>>> y = Symbol('y')

>>> Derivative(x**2, x, evaluate=True)
2*x
>>> Derivative(Derivative(f(x,y), x), y)
Derivative(f(x, y), x, y)
>>> Derivative(f(x), x, 3)
Derivative(f(x), x, x, x)
>>> Derivative(f(x, y), y, x, evaluate=True)
Derivative(f(x, y), x, y)


Now some derivatives wrt functions:

>>> Derivative(f(x)**2, f(x), evaluate=True)
2*f(x)
>>> Derivative(f(g(x)), x, evaluate=True)
Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), (_xi_1,), (g(x),))

doit_numerically(a, b)[source]

Evaluate the derivative at z numerically.

When we can represent derivatives at a point, this should be folded into the normal evalf. For now, we need a special method.

### diff¶

sympy.core.function.diff(f, *symbols, **kwargs)[source]

Differentiate f with respect to symbols.

This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x).

You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False.

Derivative

References

http://documents.wolfram.com/v5/Built-inFunctions/AlgebraicComputation/
Calculus/D.html

Examples

>>> from sympy import sin, cos, Function, diff
>>> from sympy.abc import x, y
>>> f = Function('f')

>>> diff(sin(x), x)
cos(x)
>>> diff(f(x), x, x, x)
Derivative(f(x), x, x, x)
>>> diff(f(x), x, 3)
Derivative(f(x), x, x, x)
>>> diff(sin(x)*cos(y), x, 2, y, 2)
sin(x)*cos(y)

>>> type(diff(sin(x), x))
cos
>>> type(diff(sin(x), x, evaluate=False))
<class 'sympy.core.function.Derivative'>
>>> type(diff(sin(x), x, 0))
sin
>>> type(diff(sin(x), x, 0, evaluate=False))
sin

>>> diff(sin(x))
cos(x)
>>> diff(sin(x*y))
Traceback (most recent call last):
...
ValueError: specify differentiation variables to differentiate sin(x*y)


Note that diff(sin(x)) syntax is meant only for convenience in interactive sessions and should be avoided in library code.

### FunctionClass¶

class sympy.core.function.FunctionClass(*args, **kws)[source]

Base class for function classes. FunctionClass is a subclass of type.

Use Function(‘<function name>’ [ , signature ]) to create undefined function classes.

### Function¶

class sympy.core.function.Function[source]

Base class for applied mathematical functions.

It also serves as a constructor for undefined function classes.

Examples

First example shows how to use Function as a constructor for undefined function classes:

>>> from sympy import Function, Symbol
>>> x = Symbol('x')
>>> f = Function('f')
>>> g = Function('g')(x)
>>> f
f
>>> f(x)
f(x)
>>> g
g(x)
>>> f(x).diff(x)
Derivative(f(x), x)
>>> g.diff(x)
Derivative(g(x), x)


In the following example Function is used as a base class for my_func that represents a mathematical function my_func. Suppose that it is well known, that my_func(0) is 1 and my_func at infinity goes to 0, so we want those two simplifications to occur automatically. Suppose also that my_func(x) is real exactly when x is real. Here is an implementation that honours those requirements:

>>> from sympy import Function, S, oo, I, sin
>>> class my_func(Function):
...
...     nargs = 1
...
...     @classmethod
...     def eval(cls, x):
...         if x.is_Number:
...             if x is S.Zero:
...                 return S.One
...             elif x is S.Infinity:
...                 return S.Zero
...
...     def _eval_is_real(self):
...         return self.args[0].is_real
...
>>> x = S('x')
>>> my_func(0) + sin(0)
1
>>> my_func(oo)
0
>>> my_func(3.54).n() # Not yet implemented for my_func.
my_func(3.54)
>>> my_func(I).is_real
False


In order for my_func to become useful, several other methods would need to be implemented. See source code of some of the already implemented functions for more complete examples.

Attributes

 nargs
as_base_exp()[source]

Returns the method as the 2-tuple (base, exponent).

fdiff(argindex=1)[source]

Returns the first derivative of the function.

is_commutative[source]

Returns whether the functon is commutative.

classmethod taylor_term(n, x, *previous_terms)[source]

General method for the taylor term.

This method is slow, because it differentiates n-times. Subclasses can redefine it to make it faster by using the “previous_terms”.

Note

Not all functions are the same

SymPy defines many functions (like cos and factorial). It also allows the user to create generic functions which act as argument holders. Such functions are created just like symbols:

>>> from sympy import Function, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> f(2) + f(x)
f(2) + f(x)


If you want to see which functions appear in an expression you can use the atoms method:

>>> e = (f(x) + cos(x) + 2)
>>> e.atoms(Function)
set([f(x), cos(x)])


If you just want the function you defined, not SymPy functions, the thing to search for is AppliedUndef:

>>> from sympy.core.function import AppliedUndef
>>> e.atoms(AppliedUndef)
set([f(x)])


### Subs¶

class sympy.core.function.Subs[source]

Represents unevaluated substitutions of an expression.

Subs(expr, x, x0) receives 3 arguments: an expression, a variable or list of distinct variables and a point or list of evaluation points corresponding to those variables.

Subs objects are generally useful to represent unevaluated derivatives calculated at a point.

The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity.

There’s no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression.

When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()).

A simple example:

>>> from sympy import Subs, Function, sin
>>> from sympy.abc import x, y, z
>>> f = Function('f')
>>> e = Subs(f(x).diff(x), x, y)
>>> e.subs(y, 0)
Subs(Derivative(f(x), x), (x,), (0,))
>>> e.subs(f, sin).doit()
cos(y)


An example with several variables:

>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1))
Subs(z + f(x)*sin(y), (x, y), (0, 1))
>>> _.doit()
z + f(0)*sin(1)

expr[source]

The expression on which the substitution operates

point[source]

The values for which the variables are to be substituted

variables[source]

The variables to be evaluated

### expand¶

sympy.core.function.expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]

Expand an expression using methods given as hints.

Hints evaluated unless explicitly set to False are: basic, log, multinomial, mul, power_base, and power_exp The following hints are supported but not applied unless set to True: complex, func, and trig. In addition, the following meta-hints are supported by some or all of the other hints: frac, numer, denom, modulus, and force. deep is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints.

The basic hint is used for any special rewriting of an object that should be done automatically (along with the other hints like mul) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the _eval_expand_basic method. Objects may also define their own expand methods, which are not run by default. See the API section below.

If deep is set to True (the default), things like arguments of functions are recursively expanded. Use deep=False to only expand on the top level.

If the force hint is used, assumptions about variables will be ignored in making the expansion.

Notes

• You can shut off unwanted methods:

>>> (exp(x + y)*(x + y)).expand()
x*exp(x)*exp(y) + y*exp(x)*exp(y)
>>> (exp(x + y)*(x + y)).expand(power_exp=False)
x*exp(x + y) + y*exp(x + y)
>>> (exp(x + y)*(x + y)).expand(mul=False)
(x + y)*exp(x)*exp(y)

• Use deep=False to only expand on the top level:

>>> exp(x + exp(x + y)).expand()
exp(x)*exp(exp(x)*exp(y))
>>> exp(x + exp(x + y)).expand(deep=False)
exp(x)*exp(exp(x + y))

• Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example, mul may distribute multiplications and prevent log and power_base from expanding them. Also, if mul is applied before multinomial, the expression might not be fully distributed. The solution is to use the various expand_hint helper functions or to use hint=False to this function to finely control which hints are applied. Here are some examples:

>>> from sympy import expand_log, expand, expand_mul, expand_power_base
>>> x, y, z = symbols('x,y,z', positive=True)

>>> expand(log(x*(y + z)))
log(x) + log(y + z)


Here, we see that log was applied before mul. To get the log expanded form, either of the following will work:

>>> expand_log(log(x*(y + z)))
log(x) + log(y + z)
>>> expand(log(x*(y + z)), mul=False)
log(x) + log(y + z)


A similar thing can happen with the power_base hint:

>>> expand((x*(y + z))**x)
(x*y + x*z)**x


To get the power_base expanded form, either of the following will work:

>>> expand((x*(y + z))**x, mul=False)
x**x*(y + z)**x
>>> expand_power_base((x*(y + z))**x)
x**x*(y + z)**x

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


The parts of a rational expression can be targeted:

>>> expand((x + y)*y/x/(x + 1), frac=True)
(x*y + y**2)/(x**2 + x)
>>> expand((x + y)*y/x/(x + 1), numer=True)
(x*y + y**2)/(x*(x + 1))
>>> expand((x + y)*y/x/(x + 1), denom=True)
y*(x + y)/(x**2 + x)

• The modulus meta-hint can be used to reduce the coefficients of an expression post-expansion:

>>> expand((3*x + 1)**2)
9*x**2 + 6*x + 1
>>> expand((3*x + 1)**2, modulus=5)
4*x**2 + x + 1

• Either expand() the function or .expand() the method can be used. Both are equivalent:

>>> expand((x + 1)**2)
x**2 + 2*x + 1
>>> ((x + 1)**2).expand()
x**2 + 2*x + 1


Hints

These hints are run by default

Mul

>>> from sympy import cos, exp, sin
>>> from sympy.abc import x, y, z
>>> (y*(x + z)).expand(mul=True)
x*y + y*z


Multinomial

Expand (x + y + ...)**n where n is a positive integer.

>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2


Power_exp

Expand addition in exponents into multiplied bases.

>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y


Power_base

Split powers of multiplied bases.

This only happens by default if assumptions allow, or if the force meta-hint is used:

>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z


Note that in some cases where this expansion always holds, SymPy performs it automatically:

>>> (x*y)**2
x**2*y**2


Log

Pull out power of an argument as a coefficient and split logs products into sums of logs.

Note that these only work if the arguments of the log function have the proper assumptions–the arguments must be positive and the exponents must be real–or else the force hint must be True:

>>> from sympy import log, symbols, oo
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)


Basic

This hint is intended primarily as a way for custom subclasses to enable expansion by default.

These hints are not run by default:

Complex

Split an expression into real and imaginary parts.

>>> x, y = symbols('x,y')
>>> (x + y).expand(complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))


Note that this is just a wrapper around as_real_imag(). Most objects that wish to redefine _eval_expand_complex() should consider redefining as_real_imag() instead.

Func

Expand other functions.

>>> from sympy import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)


Trig

Do trigonometric expansions.

>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(2*x).expand(trig=True)
2*sin(x)*cos(x)


Note that the forms of sin(n*x) and cos(n*x) in terms of sin(x) and cos(x) are not unique, due to the identity $$\sin^2(x) + \cos^2(x) = 1$$. The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See this MathWorld article for more information.

Api

Objects can define their own expand hints by defining _eval_expand_hint(). The function should take the form:

def _eval_expand_hint(self, **hints):
# Only apply the method to the top-level expression
...


See also the example below. Objects should define _eval_expand_hint() methods only if hint applies to that specific object. The generic _eval_expand_hint() method defined in Expr will handle the no-op case.

Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only. expand() takes care of the recursion that happens when deep=True.

You should only call _eval_expand_hint() methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpected AttributeErrors.  Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by expand(). _eval_expand_hint() should generally not be used at all outside of an _eval_expand_hint() method. If you want to apply a specific expansion from within another method, use the public expand() function, method, or expand_hint() functions.

In order for expand to work, objects must be rebuildable by their args, i.e., obj.func(*obj.args) == obj must hold.

Expand methods are passed **hints so that expand hints may use ‘metahints’–hints that control how different expand methods are applied. For example, the force=True hint described above that causes expand(log=True) to ignore assumptions is such a metahint. The deep meta-hint is handled exclusively by expand() and is not passed to _eval_expand_hint() methods.

Note that expansion hints should generally be methods that perform some kind of ‘expansion’. For hints that simply rewrite an expression, use the .rewrite() API.

Example

>>> from sympy import Expr, sympify
>>> class MyClass(Expr):
...     def __new__(cls, *args):
...         args = sympify(args)
...         return Expr.__new__(cls, *args)
...
...     def _eval_expand_double(self, **hints):
...         '''
...         Doubles the args of MyClass.
...
...         If there more than four args, doubling is not performed,
...         unless force=True is also used (False by default).
...         '''
...         force = hints.pop('force', False)
...         if not force and len(self.args) > 4:
...             return self
...         return self.func(*(self.args + self.args))
...
>>> a = MyClass(1, 2, MyClass(3, 4))
>>> a
MyClass(1, 2, MyClass(3, 4))
>>> a.expand(double=True)
MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
>>> a.expand(double=True, deep=False)
MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))

>>> b = MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True)
MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True, force=True)
MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)


### PoleError¶

class sympy.core.function.PoleError[source]

### count_ops¶

sympy.core.function.count_ops(expr, visual=False)[source]

Return a representation (integer or expression) of the operations in expr.

If visual is False (default) then the sum of the coefficients of the visual expression will be returned.

If visual is True then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur.

If expr is an iterable, the sum of the op counts of the items will be returned.

Examples

>>> from sympy.abc import a, b, x, y
>>> from sympy import sin, count_ops


Although there isn’t a SUB object, minus signs are interpreted as either negations or subtractions:

>>> (x - y).count_ops(visual=True)
SUB
>>> (-x).count_ops(visual=True)
NEG


Here, there are two Adds and a Pow:

>>> (1 + a + b**2).count_ops(visual=True)


In the following, an Add, Mul, Pow and two functions:

>>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
ADD + MUL + POW + 2*SIN


for a total of 5:

>>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
5


Note that “what you type” is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs:

>>> (1/x/y).count_ops(visual=True)
DIV + MUL


The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial:

>>> eq=x*(1 + x*(2 + x*(3 + x)))
>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
-MUL + 3*POW


The count_ops function also handles iterables:

>>> count_ops([x, sin(x), None, True, x + 2], visual=False)
2
>>> count_ops([x, sin(x), None, True, x + 2], visual=True)
>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)


### expand_mul¶

sympy.core.function.expand_mul(expr, deep=True)[source]

Wrapper around expand that only uses the mul hint. See the expand docstring for more information.

Examples

>>> from sympy import symbols, expand_mul, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)


### expand_log¶

sympy.core.function.expand_log(expr, deep=True, force=False)[source]

Wrapper around expand that only uses the log hint. See the expand docstring for more information.

Examples

>>> from sympy import symbols, expand_log, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
(x + y)*(log(x) + 2*log(y))*exp(x + y)


### expand_func¶

sympy.core.function.expand_func(expr, deep=True)[source]

Wrapper around expand that only uses the func hint. See the expand docstring for more information.

Examples

>>> from sympy import expand_func, gamma
>>> from sympy.abc import x
>>> expand_func(gamma(x + 2))
x*(x + 1)*gamma(x)


### expand_trig¶

sympy.core.function.expand_trig(expr, deep=True)[source]

Wrapper around expand that only uses the trig hint. See the expand docstring for more information.

Examples

>>> from sympy import expand_trig, sin, cos
>>> from sympy.abc import x, y
>>> expand_trig(sin(x+y)*(x+y))
(x + y)*(sin(x)*cos(y) + sin(y)*cos(x))


### expand_complex¶

sympy.core.function.expand_complex(expr, deep=True)[source]

Wrapper around expand that only uses the complex hint. See the expand docstring for more information.

Expr.as_real_imag

Examples

>>> from sympy import expand_complex, exp, sqrt, I
>>> from sympy.abc import z
>>> expand_complex(exp(z))
I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z))
>>> expand_complex(sqrt(I))
sqrt(2)/2 + sqrt(2)*I/2


### expand_multinomial¶

sympy.core.function.expand_multinomial(expr, deep=True)[source]

Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information.

Examples

>>> from sympy import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomial((x + exp(x + 1))**2)
x**2 + 2*x*exp(x + 1) + exp(2*x + 2)


### expand_power_exp¶

sympy.core.function.expand_power_exp(expr, deep=True)[source]

Wrapper around expand that only uses the power_exp hint.

Examples

>>> from sympy import expand_power_exp
>>> from sympy.abc import x, y
>>> expand_power_exp(x**(y + 2))
x**2*x**y


### expand_power_base¶

sympy.core.function.expand_power_base(expr, deep=True, force=False)[source]

Wrapper around expand that only uses the power_base hint.

A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power’s base and exponent allow.

deep=False (default is True) will only apply to the top-level expression.

force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer.

>>> from sympy.abc import x, y, z
>>> from sympy import expand_power_base, sin, cos, exp

>>> (x*y)**2
x**2*y**2

>>> (2*x)**y
(2*x)**y
>>> expand_power_base(_)
2**y*x**y

>>> expand_power_base((x*y)**z)
(x*y)**z
>>> expand_power_base((x*y)**z, force=True)
x**z*y**z
>>> expand_power_base(sin((x*y)**z), deep=False)
sin((x*y)**z)
>>> expand_power_base(sin((x*y)**z), force=True)
sin(x**z*y**z)

>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y)
2**y*sin(x)**y + 2**y*cos(x)**y

>>> expand_power_base((2*exp(y))**x)
2**x*exp(y)**x

>>> expand_power_base((2*cos(x))**y)
2**y*cos(x)**y


Notice that sums are left untouched. If this is not the desired behavior, apply full expand() to the expression:

>>> expand_power_base(((x+y)*z)**2)
z**2*(x + y)**2
>>> (((x+y)*z)**2).expand()
x**2*z**2 + 2*x*y*z**2 + y**2*z**2

>>> expand_power_base((2*y)**(1+z))
2**(z + 1)*y**(z + 1)
>>> ((2*y)**(1+z)).expand()
2*2**z*y*y**z


### nfloat¶

sympy.core.function.nfloat(expr, n=15, exponent=False)[source]

Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True).

Examples

>>> from sympy.core.function import nfloat
>>> from sympy.abc import x, y
>>> from sympy import cos, pi, S, sqrt
>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y))
x**4 + 0.5*x + sqrt(y) + 1.5
>>> nfloat(x**4 + sqrt(y), exponent=True)
x**4.0 + y**0.5


## evalf¶

### PrecisionExhausted¶

class sympy.core.evalf.PrecisionExhausted[source]

### N¶

class sympy.core.evalf.N[source]

Calls x.evalf(n, **options).

Both .n() and N() are equivalent to .evalf(); use the one that you like better. See also the docstring of .evalf() for information on the options.

Examples

>>> from sympy import Sum, Symbol, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291


## containers¶

### Tuple¶

class sympy.core.containers.Tuple[source]

Wrapper around the builtin tuple object

The Tuple is a subclass of Basic, so that it works well in the SymPy framework. The wrapped tuple is available as self.args, but you can also access elements or slices with [:] syntax.

>>> from sympy import symbols
>>> from sympy.core.containers import Tuple
>>> a, b, c, d = symbols('a b c d')
>>> Tuple(a, b, c)[1:]
(b, c)
>>> Tuple(a, b, c).subs(a, d)
(d, b, c)


### Dict¶

class sympy.core.containers.Dict[source]

Wrapper around the builtin dict object

The Dict is a subclass of Basic, so that it works well in the SymPy framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be changed afterwards. Otherwise it behaves identically to the Python dict.

>>> from sympy import S
>>> from sympy.core.containers import Dict

>>> D = Dict({1: 'one', 2: 'two'})
>>> for key in D:
...    if key == 1:
...        print key, D[key]
1 one


The args are sympified so the 1 and 2 are Integers and the values are Symbols. Queries automatically sympify args so the following work:

>>> 1 in D
True
>>> D.has('one') # searches keys and values
True
>>> 'one' in D # not in the keys
False
>>> D[1]
one

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
items() → list of D's (key, value) pairs, as 2-tuples[source]
keys() → list of D's keys[source]
values() → list of D's values[source]

## compatibility¶

### iterable¶

sympy.core.compatibility.iterable(i, exclude=(<type 'basestring'>, <type 'dict'>))[source]

Return a boolean indicating whether i is an iterable in the sympy sense.

When sympy is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure python definition, make exclude=None. To exclude multiple items, pass them as a tuple.

Examples

>>> from sympy.utilities.iterables import iterable
>>> from sympy import Tuple
>>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
>>> for i in things:
...     print iterable(i), type(i)
True <... 'list'>
True <... 'tuple'>
True <... 'set'>
True <class 'sympy.core.containers.Tuple'>
True <... 'generator'>
False <... 'dict'>
False <... 'str'>
False <... 'int'>

>>> iterable({}, exclude=None)
True
>>> iterable({}, exclude=str)
True
>>> iterable("no", exclude=str)
False


### is_sequence¶

sympy.core.compatibility.is_sequence(i, include=None)[source]

Return a boolean indicating whether i is a sequence in the sympy sense. If anything that fails the test below should be included as being a sequence for your application, set ‘include’ to that object’s type; multiple types should be passed as a tuple of types.

Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence.

Examples

>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True


### set_intersection¶

sympy.core.compatibility.set_intersection(*sets)[source]

Return the intersection of all the given sets.

As of Python 2.6 you can write set.intersection(*sets).

Examples

>>> from sympy.core.compatibility import set_intersection
>>> set_intersection(set([1, 2]), set([2, 3]))
set([2])
>>> set_intersection()
set()


### set_union¶

sympy.core.compatibility.set_union(*sets)[source]

Return the union of all the given sets.

As of Python 2.6 you can write set.union(*sets).

>>> from sympy.core.compatibility import set_union
>>> set_union(set([1, 2]), set([2, 3]))
set([1, 2, 3])
>>> set_union()
set()


### as_int¶

sympy.core.compatibility.as_int(n)[source]

Convert the argument to a builtin integer.

The return value is guaranteed to be equal to the input. ValueError is raised if the input has a non-integral value.

Examples

>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
>>> 3.0
3.0
>>> as_int(3.0) # convert to int and test for equality
3
>>> int(sqrt(10))
3
>>> as_int(sqrt(10))
Traceback (most recent call last):
...
ValueError: ... is not an integer


## exprtools¶

### gcd_terms¶

sympy.core.exprtools.gcd_terms(terms, isprimitive=False, clear=True, fraction=True)[source]

Compute the GCD of terms and put them together.

terms can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum.

If isprimitive is True the _gcd_terms will not run the primitive method on the terms.

clear controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1.

fraction, when True (default), will put the expression over a common denominator.

Examples

>>> from sympy.core import gcd_terms
>>> from sympy.abc import x, y

>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
>>> gcd_terms(x/2 + 1)
(x + 2)/2
>>> gcd_terms(x/2 + 1, clear=False)
x/2 + 1
>>> gcd_terms(x/2 + y/2, clear=False)
(x + y)/2
>>> gcd_terms(x/2 + 1/x)
(x**2 + 2)/(2*x)
>>> gcd_terms(x/2 + 1/x, fraction=False)
(x + 2/x)/2
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
x/2 + 1/x

>>> gcd_terms(x/2/y + 1/x/y)
(x**2 + 2)/(2*x*y)
>>> gcd_terms(x/2/y + 1/x/y, fraction=False, clear=False)
(x + 2/x)/(2*y)


### factor_terms¶

Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed.

If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr.

If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients.

If fraction=True (default is False) then a common denominator will be constructed for the expression.

Examples

>>> from sympy import factor_terms, Symbol, Mul, primitive
>>> from sympy.abc import x, y
>>> factor_terms(x + x*(2 + 4*y)**3)
x*(8*(2*y + 1)**3 + 1)
>>> A = Symbol('A', commutative=False)
>>> factor_terms(x*A + x*A + x*y*A)
x*(y*A + 2*A)


When clear is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions:

>>> factor_terms(x/2 + 1, clear=False)
x/2 + 1
>>> factor_terms(x/2 + 1, clear=True)
(x + 2)/2


This only applies when there is a single Add that the coefficient multiplies:

>>> factor_terms(x*y/2 + y, clear=True)
y*(x + 2)/2
>>> factor_terms(x*y/2 + y, clear=False) == _
True