esys.escript.symbolic.functions Package

Classes

class esys.escript.symbolic.functions.Abs

Bases: sympy.core.function.Function

Return the absolute value of the argument.

This is an extension of the built-in function abs() to accept symbolic values. If you pass a SymPy expression to the built-in abs(), it will pass it automatically to Abs().

Examples

>>> from sympy import Abs, Symbol, S
>>> Abs(-1)
1
>>> x = Symbol('x', real=True)
>>> Abs(-x)
Abs(x)
>>> Abs(x**2)
x**2
>>> abs(-x) # The Python built-in
Abs(x)

Note that the Python built-in will return either an Expr or int depending on the argument:

>>> type(abs(-1))
<type 'int'>
>>> type(abs(S.NegativeOne))
<class 'sympy.core.numbers.One'>

Abs will always return a sympy object.

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'negative': False, 'nonnegative': True, 'complex': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.Basic

Bases: sympy.core.assumptions.AssumeMeths

Base class for all objects in sympy.

Conventions:

1) When you want to access parameters of some instance, always use .args: Example:

>>> 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 “_”). Example:

>>> cot(x)._args    #don't use this, use cot(x).args instead
(x,)
args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

as_poly(*gens, **args)

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

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
classmethod class_key()

Nice order of classes.

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
doit(**hints)

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)

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)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

The top-level function in an expression.

The following should hold for all objects:

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

Example:

>>> 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)

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_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = False
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_positive
is_prime
is_rational
is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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(order=None)

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, x**(1/2), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), x**(1/2), x, x**(3/2), x**2]
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
class esys.escript.symbolic.functions.Dij

Bases: sympy.core.function.Function

Represents the Kronecker Delta Function

if i == j, Dij(i, j) = 1 otherwise Dij(i, j) = 0 where i, j are usually integers

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(i, j=0)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.DiracDelta

Bases: sympy.core.function.Function

DiracDelta function, and the derivatives. DiracDelta function has the following properties: 1) diff(Heaviside(x),x) = DiracDelta(x) 2) integrate(DiracDelta(x-a)*f(x),(x,-oo,oo)) = f(a)

integrate(DiracDelta(x-a)*f(x),(x,a-e,a+e)) = f(a)
  1. DiracDelta(x) = 0, for all x != 0
  2. DiracDelta(g(x)) = Sum_i(DiracDelta(x-xi)/abs(g’(xi))) Where xis are the roots of g

Derivatives of k order of DiracDelta have the following property: 5) DiracDelta(x,k) = 0, for all x!=0

For more information, see: http://mathworld.wolfram.com/DeltaFunction.html

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg, k=0)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_simple(self, x)

Tells whether the argument(args[0]) of DiracDelta is a linear expression in x.

x can be:

  • a symbol
>>> from sympy import DiracDelta, cos
>>> from sympy.abc import x, y
>>> DiracDelta(x*y).is_simple(x)
True
>>> DiracDelta(x*y).is_simple(y)
True
>>> DiracDelta(x**2+x-2).is_simple(x)
False
>>> DiracDelta(cos(x)).is_simple(x)
False
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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(self, x)

Compute a simplified representation of the function using property number 4.

x can be:

  • a symbol
>>> from sympy import DiracDelta
>>> from sympy.abc import x, y
>>> DiracDelta(x*y).simplify(x)
DiracDelta(x)/Abs(y)
>>> DiracDelta(x*y).simplify(y)
DiracDelta(y)/Abs(x)
>>> DiracDelta(x**2 + x - 2).simplify(x)
DiracDelta(x - 1)/3 + DiracDelta(x + 2)/3
sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.FallingFactorial

Bases: sympy.functions.combinatorial.factorials.CombinatorialFunction

Falling factorial (related to rising factorial) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by

ff(x, k) = x * (x-1) * ... * (x - k+1)

where ‘x’ can be arbitrary expression and ‘k’ is an integer. For more information check “Concrete mathematics” by Graham, pp. 66 or visit http://mathworld.wolfram.com/FallingFactorial.html page.

>>> from sympy import ff
>>> from sympy.abc import x
>>> ff(x, 0)
1
>>> ff(5, 5)
120
>>> ff(x, 5) == x*(x-1)*(x-2)*(x-3)*(x-4)
True
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(x, k)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.Heaviside

Bases: sympy.core.function.Function

Heaviside Piecewise function. Heaviside function has the following properties: 1) diff(Heaviside(x),x) = DiracDelta(x)

( 0, if x<0
  1. Heaviside(x) = < [*] 1/2 if x==0

    ( 1, if x>0

[*]Regarding to the value at 0, Mathematica adopt the value H(0)=1, and Maple H(0)=undefined

I think is better to have H(0)=1/2, due to the following: integrate(DiracDelta(x),x) = Heaviside(x) integrate(DiracDelta(x),(x,-oo,oo)) = 1

and since DiracDelta is a symmetric function, integrate(DiracDelta(x),(x,0,oo)) should be 1/2 in fact, that is what maple returns.

If we take Heaviside(0)=1/2, we would have integrate(DiracDelta(x),(x,0,oo)) = Heaviside(oo)-Heaviside(0)=1-1/2= 1/2 and integrate(DiracDelta(x),(x,-oo,0)) = Heaviside(0)-Heaviside(-oo)=1/2-0= 1/2

If we consider, instead Heaviside(0)=1, we would have integrate(DiracDelta(x),(x,0,oo)) = Heaviside(oo)-Heaviside(0) = 0 and integrate(DiracDelta(x),(x,-oo,0)) = Heaviside(0)-Heaviside(-oo) = 1

For more information, see: http://mathworld.wolfram.com/HeavisideStepFunction.html

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.L2

Bases: sympy.core.function.Function

Returns the L2 norm of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.LambertW

Bases: sympy.core.function.Function

Lambert W function, defined as the inverse function of x*exp(x). This function represents the principal branch of this inverse function, which like the natural logarithm is multivalued.

For more information, see: http://en.wikipedia.org/wiki/Lambert_W_function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.LeviCivita

Bases: sympy.core.function.Function

Represent the Levi-Civita symbol.

For even permutations of indices it returns 1, for odd permutations -1, and for everything else (a repeated index) it returns 0.

Thus it represents an alternating pseudotensor.

>>> from sympy import LeviCivita, symbols
>>> LeviCivita(1,2,3)
1
>>> LeviCivita(1,3,2)
-1
>>> LeviCivita(1,2,2)
0
>>> i,j,k = symbols('i j k')
>>> LeviCivita(i,j,k)
LeviCivita(i, j, k)
>>> LeviCivita(i,j,i)
0
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit()
dummy_eq(other, symbol=None)

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
classmethod eval(*args)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.Max

Bases: sympy.functions.elementary.miscellaneous.MinMaxBase, sympy.core.function.Application, sympy.core.basic.Basic

Return, if possible, the maximum value of the list.

When number of arguments is equal one, then return this argument.

When number of arguments is equal two, then return, if possible, the value from (a, b) that is >= the other.

In common case, when the length of list greater than 2, the task is more complicated. Return only the arguments, which are greater than others, if it is possible to determine directional relation.

If is not possible to determine such a relation, return a partially evaluated result.

Assumptions are used to make the decision too.

Also, only comparable arguments are permitted.

>>> from sympy import Max, Symbol, oo
>>> from sympy.abc import x, y
>>> p = Symbol('p', positive=True)
>>> n = Symbol('n', negative=True)
>>> Max(x, -2)                  
Max(x, -2)
>>> Max(x, -2).subs(x, 3)
3
>>> Max(p, -2)
p
>>> Max(x, y)                   
Max(x, y)
>>> Max(x, y) == Max(y, x)
True
>>> Max(x, Max(y, z))           
Max(x, y, z)
>>> Max(n, 8, p, 7, -oo)        
Max(8, p)
>>> Max (1, x, oo)
oo

The task can be considered as searching of supremums in the directed complete partial orders [1]_.

The source values are sequentially allocated by the isolated subsets in which supremums are searched and result as Max arguments.

If the resulted supremum is single, then it is returned.

The isolated subsets are the sets of values which are only the comparable with each other in the current set. E.g. natural numbers are comparable with each other, but not comparable with the x symbol. Another example: the symbol x with negative assumption is comparable with a natural number.

Also there are “least” elements, which are comparable with all others, and have a zero property (maximum or minimum for all elements). E.g. oo. In case of it the allocation operation is terminated and only this value is returned.

Assumption:
  • if A > B > C then A > C
  • if A==B then B can be removed

[1] http://en.wikipedia.org/wiki/Directed_complete_partial_order [2] http://en.wikipedia.org/wiki/Lattice_(order)

Min() : find minimum values

apart(x=None, **args)

See the apart function in sympy.polys

args
args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod class_key()

Nice order of classes.

coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'commutative': True}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

find(query, group=False)

Find all subexpressions matching a query.

classmethod flatten(seq)
free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
identity = -oo
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative = True
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

classmethod make_args(expr)

Return a sequence of elements args such that cls(*args) == expr

>>> from sympy import Symbol, Mul, Add
>>> x, y = map(Symbol, 'xy')
>>> Mul.make_args(x*y)
(x, y)
>>> Add.make_args(x*y)
(x*y,)
>>> set(Add.make_args(x*y + y)) == set([y, x*y])
True
match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

zero = oo
class esys.escript.symbolic.functions.Min

Bases: sympy.functions.elementary.miscellaneous.MinMaxBase, sympy.core.function.Application, sympy.core.basic.Basic

Return, if possible, the minimum value of the list.

>>> from sympy import Min, Symbol, oo
>>> from sympy.abc import x, y
>>> p = Symbol('p', positive=True)
>>> n = Symbol('n', negative=True)
>>> Min(x, -2)                  
Min(x, -2)
>>> Min(x, -2).subs(x, 3)
-2
>>> Min(p, -3)
-3
>>> Min(x, y)                   
Min(x, y)
>>> Min(n, 8, p, -7, p, oo)     
Min(n, -7)

Max() : find maximum values

apart(x=None, **args)

See the apart function in sympy.polys

args
args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod class_key()

Nice order of classes.

coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'commutative': True}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

find(query, group=False)

Find all subexpressions matching a query.

classmethod flatten(seq)
free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
identity = oo
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative = True
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

classmethod make_args(expr)

Return a sequence of elements args such that cls(*args) == expr

>>> from sympy import Symbol, Mul, Add
>>> x, y = map(Symbol, 'xy')
>>> Mul.make_args(x*y)
(x, y)
>>> Add.make_args(x*y)
(x*y,)
>>> set(Add.make_args(x*y + y)) == set([y, x*y])
True
match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

zero = -oo
class esys.escript.symbolic.functions.Piecewise

Bases: sympy.core.function.Function

Represents a piecewise function.

Piecewise( (expr,cond), (expr,cond), ... )
  • Each argument is a 2-tuple defining a expression and condition
  • The conds are evaluated in turn returning the first that is True. If any of the evaluated conds are not determined explicitly False, e.g. x < 1, the function is returned in symbolic form.
  • If the function is evaluated at a place where all conditions are False, a ValueError exception will be raised.
  • Pairs where the cond is explicitly False, will be removed.
>>> from sympy import Piecewise, log
>>> from sympy.abc import x
>>> f = x**2
>>> g = log(x)
>>> p = Piecewise( (0, x<-1), (f, x<=1), (g, True))
>>> p.subs(x,1)
1
>>> p.subs(x,5)
log(5)
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)
dummy_eq(other, symbol=None)

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
classmethod eval(*args)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = True
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.RisingFactorial

Bases: sympy.functions.combinatorial.factorials.CombinatorialFunction

Rising factorial (also called Pochhammer symbol) is a double valued function arising in concrete mathematics, hypergeometric functions and series expansions. It is defined by

rf(x, k) = x * (x+1) * ... * (x + k-1)

where ‘x’ can be arbitrary expression and ‘k’ is an integer. For more information check “Concrete mathematics” by Graham, pp. 66 or visit http://mathworld.wolfram.com/RisingFactorial.html page.

>>> from sympy import rf
>>> from sympy.abc import x
>>> rf(x, 0)
1
>>> rf(1, 5)
120
>>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
True
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(x, k)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.abs

Bases: sympy.core.function.Function

Returns the absolute value of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.acos

Bases: sympy.core.function.Function

acos(x) -> Returns the arc cosine of x (measured in radians)
acos(x) will evaluate automatically in the cases oo, -oo, 0, 1, -1
>>> from sympy import acos, oo, pi
>>> acos(1)
0
>>> acos(0)
pi/2
>>> acos(oo)
(oo)*I
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.acosh

Bases: sympy.core.function.Function

acosh(x) -> Returns the inverse hyperbolic cosine of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.acot

Bases: sympy.core.function.Function

acot(x) -> Returns the arc cotangent of x (measured in radians)
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.acoth

Bases: sympy.core.function.Function

acoth(x) -> Returns the inverse hyperbolic cotangent of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.arg

Bases: sympy.core.function.Function

Returns the argument (in radians) of a complex number

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.asin

Bases: sympy.core.function.Function

asin(x) -> Returns the arc sine of x (measured in radians)
asin(x) will evaluate automatically in the cases oo, -oo, 0, 1, -1
>>> from sympy import asin, oo, pi
>>> asin(1)
pi/2
>>> asin(-1)
-pi/2
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.asinh

Bases: sympy.core.function.Function

asinh(x) -> Returns the inverse hyperbolic sine of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.assoc_legendre

Bases: sympy.core.function.Function

assoc_legendre(n,m, x) gives P_nm(x), where n and m are the degree and order or an expression which is related to the nth order Legendre polynomial, P_n(x) in the following manner:

P_nm(x) = (-1)**m * (1 - x**2)**(m/2) * diff(P_n(x), x, m)

Associated Legendre polynomial are orthogonal on [-1, 1] with:

  • weight = 1 for the same m, and different n.
  • weight = 1/(1-x**2) for the same n, and different m.
>>> from sympy import assoc_legendre
>>> from sympy.abc import x
>>> assoc_legendre(0,0, x)
1
>>> assoc_legendre(1,0, x)
x
>>> assoc_legendre(1,1, x)
-(-x**2 + 1)**(1/2)
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
classmethod calc(n, m)
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, m, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 3
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.atan

Bases: sympy.core.function.Function

atan(x) -> Returns the arc tangent of x (measured in radians)
atan(x) will evaluate automatically in the cases oo, -oo, 0, 1, -1
>>> from sympy import atan, oo, pi
>>> atan(0)
0
>>> atan(1)
pi/4
>>> atan(oo)
pi/2
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.atan2

Bases: sympy.core.function.Function

atan2(y,x) -> Returns the atan(y/x) taking two arguments y and x. Signs of both y and x are considered to determine the appropriate quadrant of atan(y/x). The range is (-pi, pi].

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(y, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.atanh

Bases: sympy.core.function.Function

atanh(x) -> Returns the inverse hyperbolic tangent of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.bell

Bases: sympy.core.function.Function

Bell numbers / Bell polynomials

bell(n) gives the nth Bell number, B_n bell(n, x) gives the nth Bell polynomial, B_n(x)

Not to be confused with Bernoulli numbers and Bernoulli polynomials, which use the same notation.

>>> from sympy import bell, Symbol
>>> [bell(n) for n in range(11)]
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
>>> bell(30)
846749014511809332450147
>>> bell(4, Symbol('t'))
t**4 + 6*t**3 + 7*t**2 + t
The Bell numbers satisfy B_0 = 1 and

/ n - 1

B = ) | | * B .
n /___ k / k
k = 0
They are also given by
oo

___ n

1 k

B = - * ) –.
n e /___ k!
k = 0
The Bell polynomials are given by B_0(x) = 1 and

/ n - 1

B (x) = x * ) | | * B (x).
n /___ k - 1 / k-1
k = 1
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, sym=None)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.bernoulli

Bases: sympy.core.function.Function

Bernoulli numbers / Bernoulli polynomials

bernoulli(n) gives the nth Bernoulli number, B_n bernoulli(n, x) gives the nth Bernoulli polynomial in x, B_n(x)
>>> from sympy import bernoulli
>>> [bernoulli(n) for n in range(11)]
[1, -1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
>>> bernoulli(1000001)
0

The Bernoulli numbers are a sequence of rational numbers defined by B_0 = 1 and the recursive relation (n > 0)

n

___

/ n + 1

0 = ) | | * B .
/___ k / k k = 0

They are also commonly defined by their exponential generating function, which is x/(exp(x) - 1). For odd indices > 1, the Bernoulli numbers are zero.

The Bernoulli polynomials satisfy the analogous formula
n

___

/ n n-k

B (x) = ) | | * B * x .
n /___ k / k
k = 0

Bernoulli numbers and Bernoulli polynomials are related as B_n(0) = B_n.

We compute Bernoulli numbers using Ramanujan’s formula

/ n + 3
B = (A(n) - S(n)) / | |
n n /

where A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6 when n = 4 (mod 6), and

[n/6]
___

/ n + 3

S(n) = ) | | * B
/___ n - 6*k / n-6*k k = 1

This formula is similar to the sum given in the definition, but cuts 2/3 of the terms. For Bernoulli polynomials, we use the formula in the definition.

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, sym=None)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.besseli

Bases: sympy.functions.special.bessel.BesselBase

Modified Bessel function of the first kind.

The Bessel I function is a solution to the modified Bessel equation

z2 d2w dz2+z dw dz+(z2+ν2)2w=0.

It can be defined as

Iν(z)=i -νJν(iz),

where Jμ(z) is the Bessel function of the first kind.

Examples

>>> from sympy import besseli
>>> from sympy.abc import z, n
>>> besseli(n, z).diff(z)
besseli(n - 1, z)/2 + besseli(n + 1, z)/2

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.besselj

Bases: sympy.functions.special.bessel.BesselBase

Bessel function of the first kind.

The Bessel J function of order ν is defined to be the function satisfying Bessel’s differential equation

z2 d2w dz2+z dw dz+(z2-ν2)w=0,

with Laurent expansion

Jν(z)=zν 1 Γ(ν+1)2ν+O(z2),

if ν is not a negative integer. If ν=-n <0 is a negative integer, then the definition is

J -n(z)=(-1)nJn(z).

Examples

Create a bessel function object:

>>> from sympy import besselj, jn
>>> from sympy.abc import z, n
>>> b = besselj(n, z)

Differentiate it:

>>> b.diff(z)
besselj(n - 1, z)/2 - besselj(n + 1, z)/2

Rewrite in terms of spherical bessel functions:

>>> b.rewrite(jn)
2**(1/2)*z**(1/2)*jn(n - 1/2, z)/pi**(1/2)

Access the parameter and argument:

>>> b.order
n
>>> b.argument
z

References

  • Abramowitz, Milton; Stegun, Irene A., eds. (1965), “Chapter 9”, Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables
  • Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1
  • http://en.wikipedia.org/wiki/Bessel_function
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.besselk

Bases: sympy.functions.special.bessel.BesselBase

Modified Bessel function of the second kind.

The Bessel K function of order ν is defined as

Kν(z)=lim μν π 2 I -μ(z)-Iμ(z) sin(πμ),

where Iμ(z) is the modified Bessel function of the first kind.

It is a solution of the modified Bessel equation, and linearly independent from Yν.

Examples

>>> from sympy import besselk
>>> from sympy.abc import z, n
>>> besselk(n, z).diff(z)
-besselk(n - 1, z)/2 - besselk(n + 1, z)/2

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.bessely

Bases: sympy.functions.special.bessel.BesselBase

Bessel function of the second kind.

The Bessel Y function of order ν is defined as

Yν(z)=lim μν Jμ(z)cos(πμ)-J -μ(z) sin(πμ),

where Jμ(z) is the Bessel function of the first kind.

It is a solution to Bessel’s equation, and linearly independent from Jν.

Examples

>>> from sympy import bessely, yn
>>> from sympy.abc import z, n
>>> b = bessely(n, z)
>>> b.diff(z)
bessely(n - 1, z)/2 - bessely(n + 1, z)/2
>>> b.rewrite(yn)
2**(1/2)*z**(1/2)*yn(n - 1/2, z)/pi**(1/2)

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.binomial

Bases: sympy.functions.combinatorial.factorials.CombinatorialFunction

Implementation of the binomial coefficient. It can be defined in two ways depending on its desired interpretation:

C(n,k) = n!/(k!(n-k)!) or C(n, k) = ff(n, k)/k!

First, in a strict combinatorial sense it defines the number of ways we can choose ‘k’ elements from a set of ‘n’ elements. In this case both arguments are nonnegative integers and binomial is computed using an efficient algorithm based on prime factorization.

The other definition is generalization for arbitrary ‘n’, however ‘k’ must also be nonnegative. This case is very useful when evaluating summations.

For the sake of convenience for negative ‘k’ this function will return zero no matter what valued is the other argument.

>>> from sympy import Symbol, Rational, binomial
>>> n = Symbol('n', integer=True)
>>> binomial(15, 8)
6435
>>> binomial(n, -1)
0
>>> [ binomial(0, i) for i in range(1)]
[1]
>>> [ binomial(1, i) for i in range(2)]
[1, 1]
>>> [ binomial(2, i) for i in range(3)]
[1, 2, 1]
>>> [ binomial(3, i) for i in range(4)]
[1, 3, 3, 1]
>>> [ binomial(4, i) for i in range(5)]
[1, 4, 6, 4, 1]
>>> binomial(Rational(5,4), 3)
-5/128
>>> binomial(n, 3)
n*(n - 2)*(n - 1)/6
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, k)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.ceiling

Bases: sympy.functions.elementary.integers.RoundFunction

Ceiling is a univariate function which returns the smallest integer value not less than its argument. Ceiling function is generalized in this implementation to complex numbers.

More information can be found in “Concrete mathematics” by Graham, pp. 87 or visit http://mathworld.wolfram.com/CeilingFunction.html.

>>> from sympy import ceiling, E, I, Float, Rational
>>> ceiling(17)
17
>>> ceiling(Rational(23, 10))
3
>>> ceiling(2*E)
6
>>> ceiling(-Float(0.567))
0
>>> ceiling(I/2)
I
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.chebyshevt

Bases: sympy.functions.special.polynomials.PolynomialSequence

chebyshevt(n, x) gives the nth Chebyshev polynomial (of the first kind) of x, T_n(x)

The Chebyshev polynomials of the first kind are orthogonal on [-1, 1] with respect to the weight 1/sqrt(1-x**2).

>>> from sympy import chebyshevt
>>> from sympy.abc import x
>>> chebyshevt(0, x)
1
>>> chebyshevt(1, x)
x
>>> chebyshevt(2, x)
2*x**2 - 1
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.chebyshevt_root

Bases: sympy.core.function.Function

chebyshev_root(n, k) returns the kth root (indexed from zero) of the nth Chebyshev polynomial of the first kind; that is, if 0 <= k < n, chebyshevt(n, chebyshevt_root(n, k)) == 0.

>>> from sympy import chebyshevt, chebyshevt_root
>>> chebyshevt_root(3, 2)
-3**(1/2)/2
>>> chebyshevt(3, chebyshevt_root(3, 2))
0
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, k)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.chebyshevu

Bases: sympy.functions.special.polynomials.PolynomialSequence

chebyshevu(n, x) gives the nth Chebyshev polynomial of the second kind of x, U_n(x)

The Chebyshev polynomials of the second kind are orthogonal on [-1, 1] with respect to the weight sqrt(1-x**2).

>>> from sympy import chebyshevu
>>> from sympy.abc import x
>>> chebyshevu(0, x)
1
>>> chebyshevu(1, x)
2*x
>>> chebyshevu(2, x)
4*x**2 - 1
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.chebyshevu_root

Bases: sympy.core.function.Function

chebyshevu_root(n, k) returns the kth root (indexed from zero) of the nth Chebyshev polynomial of the second kind; that is, if 0 <= k < n, chebyshevu(n, chebyshevu_root(n, k)) == 0.

>>> from sympy import chebyshevu, chebyshevu_root
>>> chebyshevu_root(3, 2)
-2**(1/2)/2
>>> chebyshevu(3, chebyshevu_root(3, 2))
0
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, k)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.clip

Bases: sympy.core.function.Function

Returns the argument clipped to a minimum and maximum value

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2, 3)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.conjugate

Bases: sympy.core.function.Function

Changes the sign of the imaginary part of a complex number.

>>> from sympy import conjugate, I
>>> conjugate(1 + I)
1 - I
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.cos

Bases: sympy.functions.elementary.trigonometric.TrigonometricFunction

cos(x) -> Returns the cosine of x (measured in radians)
cos(x) will evaluate automatically in the case x is a multiple of pi, pi/2, pi/3, pi/4 and pi/6.
>>> from sympy import cos, pi
>>> from sympy.abc import x
>>> cos(x**2).diff(x)
-2*x*sin(x**2)
>>> cos(1).diff(x)
0
>>> cos(pi)
-1
>>> cos(pi/2)
0
>>> cos(2*pi/3)
-1/2

L{sin}, L{tan}

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

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

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

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

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

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

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

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

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

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

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

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

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.cosh

Bases: sympy.functions.elementary.hyperbolic.HyperbolicFunction

cosh(x) -> Returns the hyperbolic cosine of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

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

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

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

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

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

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

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

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

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

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

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

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

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

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

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

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

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

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

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

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

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

getn()

Returns the order of the expression.

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

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

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

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.cot

Bases: sympy.functions.elementary.trigonometric.TrigonometricFunction

cot(x) -> Returns the cotangent of x (measured in radians)
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.coth

Bases: sympy.functions.elementary.hyperbolic.HyperbolicFunction

coth(x) -> Returns the hyperbolic cotangent of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.dirichlet_eta

Bases: sympy.core.function.Function

Dirichlet eta function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(s)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.eigenvalues

Bases: sympy.core.function.Function

Returns the Eigenvalues of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.eigenvalues_and_eigenvectors

Bases: sympy.core.function.Function

Returns the Eigenvalues and Eigenvectors of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.erf

Bases: sympy.core.function.Function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.exp

Bases: sympy.core.function.Function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()
as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
base
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
exp
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.factorial

Bases: sympy.functions.combinatorial.factorials.CombinatorialFunction

Implementation of factorial function over nonnegative integers. For the sake of convenience and simplicity of procedures using this function it is defined for negative integers and returns zero in this case.

The factorial is very important in combinatorics where it gives the number of ways in which ‘n’ objects can be permuted. It also arises in calculus, probability, number theory etc.

There is strict relation of factorial with gamma function. In fact n! = gamma(n+1) for nonnegative integers. Rewrite of this kind is very useful in case of combinatorial simplification.

Computation of the factorial is done using two algorithms. For small arguments naive product is evaluated. However for bigger input algorithm Prime-Swing is used. It is the fastest algorithm known and computes n! via prime factorization of special class of numbers, called here the ‘Swing Numbers’.

>>> from sympy import Symbol, factorial
>>> n = Symbol('n', integer=True)
>>> factorial(-2)
0
>>> factorial(0)
1
>>> factorial(7)
5040
>>> factorial(n)
n!
>>> factorial(2*n)
(2*n)!
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.factorial2

Bases: sympy.functions.combinatorial.factorials.CombinatorialFunction

The double factorial n!!, not to be confused with (n!)!

The double facotrial is defined for integers >= -1 as
,
n*(n - 2)*(n - 4)* ... * 1 for n odd
n!! = -| n*(n - 2)*(n - 4)* ... * 2 for n even
1 for n = 0, -1 ‘
>>> from sympy import factorial2, var
>>> var('n')
n
>>> factorial2(n + 1)
(n + 1)!!
>>> factorial2(5)
15
>>> factorial2(-1)
1
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

esys.escript.symbolic.functions.ff

alias of FallingFactorial

class esys.escript.symbolic.functions.fibonacci

Bases: sympy.core.function.Function

Fibonacci numbers / Fibonacci polynomials

fibonacci(n) gives the nth Fibonacci number, F_n fibonacci(n, x) gives the nth Fibonacci polynomial in x, F_n(x)
>>> from sympy import fibonacci, Symbol
>>> [fibonacci(x) for x in range(11)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fibonacci(5, Symbol('t'))
t**4 + 3*t**2 + 1

The Fibonacci numbers are the integer sequence defined by the initial terms F_0 = 0, F_1 = 1 and the two-term recurrence relation F_n = F_{n-1} + F_{n-2}.

The Fibonacci polynomials are defined by F_1(x) = 1, F_2(x) = x, and F_n(x) = x*F_{n-1}(x) + F_{n-2}(x) for n > 2. For all positive integers n, F_n(1) = F_n.

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, sym=None)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.floor

Bases: sympy.functions.elementary.integers.RoundFunction

Floor is a univariate function which returns the largest integer value not greater than its argument. However this implementation generalizes floor to complex numbers.

More information can be found in “Concrete mathematics” by Graham, pp. 87 or visit http://mathworld.wolfram.com/FloorFunction.html.

>>> from sympy import floor, E, I, Float, Rational
>>> floor(17)
17
>>> floor(Rational(23, 10))
2
>>> floor(2*E)
5
>>> floor(-Float(0.567))
-1
>>> floor(-I/2)
-I
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.gamma

Bases: sympy.core.function.Function

The gamma function returns a function which passes through the integral values of the factorial function, i.e. though defined in the complex plane, when n is an integer, gamma(n) = (n - 1)!

Reference:
http://en.wikipedia.org/wiki/Gamma_function
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.grad_n

Bases: sympy.core.function.Function

Returns the spatial gradient of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (2, 3)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.hankel1

Bases: sympy.functions.special.bessel.BesselBase

Hankel function of the first kind.

This function is defined as

Hν (1)=Jν(z)+iYν(z),

where Jν(z) is the Bessel function of the first kind, and Yν(z) is the Bessel function of the second kind.

It is a solution to Bessel’s equation.

Examples

>>> from sympy import hankel1
>>> from sympy.abc import z, n
>>> hankel1(n, z).diff(z)
hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.hankel2

Bases: sympy.functions.special.bessel.BesselBase

Hankel function of the second kind.

This function is defined as

Hν (2)=Jν(z)-iYν(z),

where Jν(z) is the Bessel function of the first kind, and Yν(z) is the Bessel function of the second kind.

It is a solution to Bessel’s equation, and linearly independent from Hν (1).

Examples

>>> from sympy import hankel2
>>> from sympy.abc import z, n
>>> hankel2(n, z).diff(z)
hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.harmonic

Bases: sympy.core.function.Function

Harmonic numbers

harmonic(n) gives the nth harmonic number, H_n

harmonic(n, m) gives the nth generalized harmonic number
of order m, H_{n,m}, where harmonic(n) == harmonic(n, 1)
>>> from sympy import harmonic, oo
>>> [harmonic(n) for n in range(6)]
[0, 1, 3/2, 11/6, 25/12, 137/60]
>>> [harmonic(n, 2) for n in range(6)]
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
>>> harmonic(oo, 2)
pi**2/6

The nth harmonic number is given by 1 + 1/2 + 1/3 + ... + 1/n. More generally,

n

___

-m

H = ) k .
n,m /___
k = 1

As n -> oo, H_{n,m} -> zeta(m) (the Riemann zeta function)

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, m=None)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.hermite

Bases: sympy.functions.special.polynomials.PolynomialSequence

hermite(n, x) gives the nth Hermite polynomial in x, H_n(x)

The Hermite polynomials are orthogonal on (-oo, oo) with respect to the weight exp(-x**2/2).

>>> from sympy import hermite
>>> from sympy.abc import x
>>> hermite(0, x)
1
>>> hermite(1, x)
2*x
>>> hermite(2, x)
4*x**2 - 2
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.hyper

Bases: sympy.functions.special.hyper.TupleParametersBase

The (generalized) hypergeometric function is defined by a series where the ratios of successive terms are a rational function of the summation index. When convergent, it is continued analytically to the largest possible domain.

The hypergeometric function depends on two vectors of parameters, called the numerator parameters ap, and the denominator parameters bq. It also has an argument z. The series definition is

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.hyper, line 17)

Unknown LaTeX command: dots

{}_pF_q\left.\left(\begin{matrix} a_1, \dots, a_p \\ b_1, \dots, b_q \end{matrix}
             \right| z \right)
= \sum_{n=0}^\infty \frac{(a_1)_n \dots (a_p)_n}{(b_1)_n \dots (b_q)_n}
                    \frac{z^n}{n!},

where

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.hyper, line 16)

Unknown LaTeX command: dots

(a)_n = (a)(a+1)\dots(a+n-1)
denotes the rising factorial.

If one of the bq is a non-positive integer then the series is undefined unless one of the a_p is a larger (i.e. smaller in magnitude) non-positive integer. If none of the bq is a non-positive integer and one of the ap is a non-positive integer, then the series reduces to a polynomial. To simplify the following discussion, we assume that none of the ap or bq is a non-positive integer. For more details, see the references.

The series converges for all z if pq, and thus defines an entire single-valued function in this case. If p=q+1 the series converges for |z|<1, and can be continued analytically into a half-plane. If p>q+1 the series is divergent for all z.

Note: The hypergeometric function constructor currently does not check if the parameters actually yield a well-defined function.

Examples

The parameters ap and bq can be passed as arbitrary iterables, for example:

>>> from sympy.functions import hyper
>>> from sympy.abc import x, n, a
>>> hyper((1, 2, 3), [3, 4], x)
hyper((1, 2, 3), (3, 4), x)

There is also pretty printing (it looks better using unicode):

>>> from sympy import pprint
>>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False)
  _
 |_  /1, 2, 3 |  \
 |   |        | x|
3  2 \  3, 4  |  /

The parameters must always be iterables, even if they are vectors of length one or zero:

>>> hyper((1, ), [], x)
hyper((1,), (), x)

But of course they may be variables (but if they depend on x then you should not expect much implemented functionality):

>>> hyper((n, a), (n**2,), x)
hyper((n, a), (n**2,), x)

The hypergeometric function generalises many named special functions. The function hyperexpand() tries to express a hypergeometric function using named special functions. For example:

>>> from sympy import hyperexpand
>>> hyperexpand(hyper([], [], x))
exp(x)

You can also use expand_func:

>>> from sympy import expand_func
>>> expand_func(x*hyper([1, 1], [2], -x))
log(x + 1)

More examples:

>>> from sympy import S
>>> hyperexpand(hyper([], [S(1)/2], -x**2/4))
cos(x)
>>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2))
asin(x)

We can also sometimes hyperexpand parametric functions:

>>> from sympy.abc import a
>>> hyperexpand(hyper([-a], [], x))
(-x + 1)**a

See Also:

  • sympy.simplify.hyperexpand()

References

ap

Numerator parameters of the hypergeometric function.

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

Argument of the hypergeometric function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
bq

Denominator parameters of the hypergeometric function.

cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
convergence_statement

Return a condition on z under which the series converges.

could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
eta

A quantity related to the convergence of the series.

classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=3)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 3
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radius_of_convergence

Compute the radius of convergence of the defining series.

Note that even if this is not oo, the function may still be evaluated outside of the radius of convergence by analytic continuation. But if this is zero, then the function is not actually defined anywhere else.

>>> from sympy.functions import hyper
>>> from sympy.abc import z
>>> hyper((1, 2), [3], z).radius_of_convergence
1
>>> hyper((1, 2, 3), [4], z).radius_of_convergence
0
>>> hyper((1, 2), (3, 4), z).radius_of_convergence
oo
radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.im

Bases: sympy.core.function.Function

Returns imaginary part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function.

>>> from sympy import re, im, E, I
>>> from sympy.abc import x, y
>>> im(2*E)
0
>>> re(2*I + 17)
17
>>> im(x*I)
re(x)
>>> im(re(x) + y)
im(y)
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'imaginary': False, 'complex': True, 'commutative': True}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.integrate

Bases: sympy.core.function.Function

Returns the integral of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.interpolate

Bases: sympy.core.function.Function

Returns the argument interpolated on the function space provided

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.jn

Bases: sympy.functions.special.bessel.SphericalBesselBase

Spherical Bessel function of the first kind.

This function is a solution to the spherical bessel equation

z2 d2w dz2+2z dw dz+(z2-ν(ν+1))w=0.

It can be defined as

jν(z)= π 2zJ ν+ 1 2(z),

where Jν(z) is the Bessel function of the first kind.

Examples

>>> from sympy import Symbol, jn, sin, cos, expand_func
>>> z = Symbol("z")
>>> print jn(0, z).expand(func=True)
sin(z)/z
>>> jn(1, z).expand(func=True) == sin(z)/z**2 - cos(z)/z
True
>>> expand_func(jn(3, z))
(-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z)

The spherical Bessel functions of integral order are calculated using the formula:

jn(z)=fn(z)sin z+(-1) n+1f -n-1(z)cos z,

where the coefficients fn(z) are available as polys.orthopolys.spherical_bessel_fn().

See also: besselj

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.legendre

Bases: sympy.functions.special.polynomials.PolynomialSequence

legendre(n, x) gives the nth Legendre polynomial of x, P_n(x)

The Legendre polynomials are orthogonal on [-1, 1] with respect to the constant weight 1. They satisfy P_n(1) = 1 for all n; further, P_n is odd for odd n and even for even n

>>> from sympy import legendre
>>> from sympy.abc import x
>>> legendre(0, x)
1
>>> legendre(1, x)
x
>>> legendre(2, x)
3*x**2/2 - 1/2
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

esys.escript.symbolic.functions.ln

alias of log

class esys.escript.symbolic.functions.log

Bases: sympy.core.function.Function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg, base=None)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.log10

Bases: sympy.core.function.Function

Returns the base-10 logarithm of the argument (same as log(x,10))

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.loggamma

Bases: sympy.core.function.Function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.lowergamma

Bases: sympy.core.function.Function

Lower incomplete gamma function

It can be defined as the meromorphic continuation of

γ(s,x)=0xt s-1e -tdt.

This can be shown to be the same as

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/gamma_functions.py:docstring of esys.escript.symbolic.functions.lowergamma, line 17)

Unknown LaTeX command: atop

\gamma(s, x) = \frac{x^s}{s} {}_1F_1\left.\left({s \atop s+1} \right| -x\right),

where 1F1 is the (confluent) hypergeometric function.

See also: gamma, uppergamma, hyper.

Examples

>>> from sympy import lowergamma, S
>>> from sympy.abc import s, x
>>> lowergamma(s, x)
lowergamma(s, x)
>>> lowergamma(3, x)
-x**2*exp(-x) - 2*x*exp(-x) + 2 - 2*exp(-x)
>>> lowergamma(-S(1)/2, x)
-2*pi**(1/2)*erf(x**(1/2)) - 2*exp(-x)/x**(1/2)

References

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(a, x)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.lucas

Bases: sympy.core.function.Function

Lucas numbers

lucas(n) gives the nth Lucas number
>>> from sympy import lucas
>>> [lucas(x) for x in range(11)]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
Lucas numbers satisfy a recurrence relation similar to that of the Fibonacci sequence, in which each term is the sum of the preceding two. They are generated by choosing the initial values L_0 = 2 and L_1 = 1.
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.maximum

Bases: sympy.core.function.Function

Returns the maximum over the arguments

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.maxval

Bases: sympy.core.function.Function

Returns the maximum value over all components of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.meijerg

Bases: sympy.functions.special.hyper.TupleParametersBase

The Meijer G-function is defined by a Mellin-Barnes type integral that resembles an inverse Mellin transform. It generalises the hypergeometric functions.

The Meijer G-function depends on four sets of parameters. There are “numerator parameters

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.meijerg, line 5)

Unknown LaTeX command: dots

a_1, \dots, a_n
and

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.meijerg, line 5)

Unknown LaTeX command: dots

a_{n+1}, \dots, a_p
, and there are “denominator parameters

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.meijerg, line 5)

Unknown LaTeX command: dots

b_1, \dots, b_m
and

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.meijerg, line 5)

Unknown LaTeX command: dots

b_{m+1}, \dots, b_q
. Confusingly, it is traditionally denoted as follows (note the position of m, n, p, q, and how they relate to the lengths of the four parameter vectors):

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/hyper.py:docstring of esys.escript.symbolic.functions.meijerg, line 21)

Unknown LaTeX command: dots

G_{p,q}^{m,n} \left.\left(\begin{matrix}a_1, \dots, a_n & a_{n+1}, \dots, a_p \\
                                b_1, \dots, b_m & b_{m+1}, \dots, b_q
                  \end{matrix} \right| z \right).

However, in sympy the four parameter vectors are always available separately (see examples), so that there is no need to keep track of the decorating sub- and super-scripts on the G symbol.

The G function is defined as the following integral:

1 2πiL j=1mΓ(bj-s) j=1nΓ(1-aj+s) j=m+1qΓ(1-bj+s) j=n+1pΓ(aj-s)zsds,

where Γ(z) is the gamma function. There are three possible contours which we will not describe in detail here (see the references). If the integral converges along more than one of them the definitions agree. The contours all separate the poles of Γ(1-aj+s) from the poles of Γ(bk-s), so in particular the G function is undefined if aj-bk >0 for some jn and km.

The conditions under which one of the contours yields a convergent integral are complicated and we do not state them here, see the references.

Note: Currently the Meijer G-function constructor does not check any convergence conditions.

Examples

You can pass the parameters either as four separate vectors:

>>> from sympy.functions import meijerg
>>> from sympy.abc import x, a
>>> from sympy.core.containers import Tuple
>>> from sympy import pprint
>>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False)
 __1, 2 /1, 2  a, 4 |  \
/__     |           | x|
\_|4, 1 \ 5         |  /

or as two nested vectors:

>>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False)
 __1, 2 /1, 2  3, 4 |  \
/__     |           | x|
\_|4, 1 \ 5         |  /

As with the hypergeometric function, the parameters may be passed as arbitrary iterables. Vectors of length zero and one also have to be passed as iterables. The parameters need not be constants, but if they depend on the argument then not much implemented functionality should be expected.

All the subvectors of parameters are available:

>>> from sympy import pprint
>>> g = meijerg([1], [2], [3], [4], x)
>>> pprint(g, use_unicode=False)
 __1, 1 /1  2 |  \
/__     |     | x|
\_|2, 2 \3  4 |  /
>>> g.an
(1,)
>>> g.ap
(1, 2)
>>> g.aother
(2,)
>>> g.bm
(3,)
>>> g.bq
(3, 4)
>>> g.bother
(4,)

The Meijer G-function generalises the hypergeometric functions. In some cases it can be expressed in terms of hypergeometric functions, using Slater’s theorem. For example:

>>> from sympy import hyperexpand
>>> from sympy.abc import a, b, c
>>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True)
x**c*gamma(-a + c + 1)*hyper((-a + c + 1,), (-b + c + 1,), -x)/gamma(-b + c + 1)

Thus the Meijer G-function also subsumes many named functions as special cases. You can use expand_func or hyperexpand to (try to) rewrite a Meijer G-function in terms of named special functions. For example:

>>> from sympy import expand_func, S
>>> expand_func(meijerg([[],[]], [[0],[]], -x))
exp(x)
>>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2))
sin(x)/pi**(1/2)

See Also:

  • sympy.simplify.hyperexpand()

References

an

First set of numerator parameters.

aother

Second set of numerator parameters.

ap

Combined numerator parameters.

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

Argument of the Meijer G-function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
bm

First set of denominator parameters.

bother

Second set of denominator parameters.

bq

Combined denominator parameters.

cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
delta

A quantity related to the convergence region of the integral, c.f. references.

diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=3)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 3
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

nu

A quantity related to the convergence region of the integral, c.f. references.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.minimum

Bases: sympy.core.function.Function

Returns the minimum over the arguments

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.minval

Bases: sympy.core.function.Function

Returns the minimum value over all components of the argument

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = None
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.polygamma

Bases: sympy.core.function.Function

The function polygamma(n, z) returns log(gamma(z)).diff(n + 1)

Reference:
http://en.wikipedia.org/wiki/Polygamma_function
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(n, z)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.re

Bases: sympy.core.function.Function

Returns real part of expression. This function performs only elementary analysis and so it will fail to decompose properly more complicated expressions. If completely simplified result is needed then use Basic.as_real_imag() or perform complex expansion on instance of this function.

>>> from sympy import re, im, I, E
>>> from sympy.abc import x, y
>>> re(2*E)
2*E
>>> re(2*I + 17)
17
>>> re(2*I)
0
>>> re(im(x) + x*I + 2)
2
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'imaginary': False, 'complex': True, 'commutative': True}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

esys.escript.symbolic.functions.rf

alias of RisingFactorial

class esys.escript.symbolic.functions.sign

Bases: sympy.core.function.Function

Return the sign of an expression, that is: -1 if expr < 0

0 if expr == 0 1 if expr > 0
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'unbounded': False, 'bounded': True}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.sin

Bases: sympy.functions.elementary.trigonometric.TrigonometricFunction

sin(x) -> Returns the sine of x (measured in radians)
sin(x) will evaluate automatically in the case x is a multiple of pi, pi/2, pi/3, pi/4 and pi/6.
>>> from sympy import sin, pi
>>> from sympy.abc import x
>>> sin(x**2).diff(x)
2*x*cos(x**2)
>>> sin(1).diff(x)
0
>>> sin(pi)
0
>>> sin(pi/2)
1
>>> sin(pi/6)
1/2

L{cos}, L{tan}

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.sinh

Bases: sympy.functions.elementary.hyperbolic.HyperbolicFunction

sinh(x) -> Returns the hyperbolic sine of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.tan

Bases: sympy.functions.elementary.trigonometric.TrigonometricFunction

tan(x) -> Returns the tangent of x (measured in radians)
tan(x) will evaluate automatically in the case x is a multiple of pi.
>>> from sympy import tan
>>> from sympy.abc import x
>>> tan(x**2).diff(x)
2*x*(tan(x**2)**2 + 1)
>>> tan(1).diff(x)
0

L{sin}, L{tan}

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.tanh

Bases: sympy.functions.elementary.hyperbolic.HyperbolicFunction

tanh(x) -> Returns the hyperbolic tangent of x
apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True, **hints)
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

inverse(argindex=1)
invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
static taylor_term(*args, **kw_args)
together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.uppergamma

Bases: sympy.core.function.Function

Upper incomplete gamma function

It can be defined as the meromorphic continuation of

Γ(s,x)=xt s-1e -tdt=Γ(s)-γ(s,x).

This can be shown to be the same as

System Message: ERROR/3 (/usr/lib/python2.7/dist-packages/sympy/functions/special/gamma_functions.py:docstring of esys.escript.symbolic.functions.uppergamma, line 18)

Unknown LaTeX command: atop

\Gamma(s, x) = \Gamma(s)
        - \frac{x^s}{s} {}_1F_1\left.\left({s \atop s+1} \right| -x\right),

where 1F1 is the (confluent) hypergeometric function.

Examples

>>> from sympy import uppergamma, S
>>> from sympy.abc import s, x
>>> uppergamma(s, x)
uppergamma(s, x)
>>> uppergamma(3, x)
x**2*exp(-x) + 2*x*exp(-x) + 2*exp(-x)
>>> uppergamma(-S(1)/2, x)
-2*pi**(1/2)*(-erf(x**(1/2)) + 1) + 2*exp(-x)/x**(1/2)

See also: gamma, lowergamma, hyper.

References

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(a, z)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.whereNegative

Bases: sympy.core.function.Function

Returns: 1 where expr < 0 0 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.whereNonNegative

Bases: sympy.core.function.Function

Returns: 0 where expr < 0 1 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.whereNonPositive

Bases: sympy.core.function.Function

Returns: 0 where expr > 0 1 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.whereNonZero

Bases: sympy.core.function.Function

Returns: 0 where expr == 0 1 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.wherePositive

Bases: sympy.core.function.Function

Returns: 1 where expr > 0 0 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.whereZero

Bases: sympy.core.function.Function

Returns: 1 where expr == 0 0 else

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {'real': True, 'commutative': True, 'unbounded': False, 'negative': False, 'nonnegative': True, 'complex': True, 'bounded': True, 'imaginary': False}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(arg)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded = True
is_commutative = True
is_comparable
is_complex = True
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary = False
is_infinitesimal
is_integer
is_irrational
is_negative = False
is_noninteger
is_nonnegative = True
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real = True
is_unbounded = False
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 1
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.yn

Bases: sympy.functions.special.bessel.SphericalBesselBase

Spherical Bessel function of the second kind.

This function is another solution to the spherical bessel equation, and linearly independent from jn. It can be defined as

jν(z)= π 2zY ν+ 1 2(z),

where Yν(z) is the Bessel function of the second kind.

Examples

>>> from sympy import Symbol, yn, sin, cos, expand_func
>>> z = Symbol("z")
>>> print expand_func(yn(0, z))
-cos(z)/z
>>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z
True

For integral orders n, yn is calculated using the formula:

yn(z)=(-1) n+1j -n-1(z)

See also: besselj, bessely, jn

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
argument

The argument of the bessel-type function.

as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(*args)

Returns a canonical form of cls applied to arguments args.

The eval() method is called when the class cls is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class cls should be unmodified, return None.

@classmethod def eval(cls, arg):

if arg is S.NaN:
return S.NaN

if arg is S.Zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, C.Mul):

coeff, terms = arg.as_coeff_mul() if coeff is not S.One:

return cls(coeff) * cls(arg._new_rawargs(*terms))
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=2)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = 2
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

order

The order of the bessel-type function.

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

class esys.escript.symbolic.functions.zeta

Bases: sympy.core.function.Function

apart(x=None, **args)

See the apart function in sympy.polys

args

Returns a tuple of arguments of ‘self’.

Example:

>>> 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

Note for developers: Never use self._args, always use self.args. Only when you are creating your own new function, use _args in the __new__. Don’t override .args() from Basic (so that it’s easy to change the interface in the future if needed).

args_cnc()

treat self as Mul and split it into tuple (set, list) where set contains the commutative parts and list contains the ordered non-commutative args.

A special treatment is that -1 is separated from a Rational:

>>> from sympy import symbols
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[set([-1, 2, x, y]), []]
>>> (-2*x*A*B*y).args_cnc()
[set([-1, 2, x, y]), [A, B]]

The arg is treated as a Mul:

>>> (-2 + x + A).args_cnc()
[set(), [x - 2 + A]]
as_base_exp()
as_coeff_Mul()

Efficiently extract the coefficient of a product.

as_coeff_add(*deps)

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
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x + y).as_coeff_add()
(3, (y, x))
>>> (3 + x +y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x)

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_factors(*deps)
as_coeff_mul(*deps)

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)
as_coefficient(expr)

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

>>> 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_expr(*gens)

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)

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(mul=True) to change Add or Mul into Add
  • .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:

– self is an Add

>>> 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=1)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=0)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=0)
(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)

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))
See also: .separatevars(), .expand(log=True),
.as_two_terms(), .as_coeff_add(), .as_coeff_mul()
as_leading_term(*args, **kw_args)

Returns the leading term.

Example:

>>> 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)

Note:

self is assumed to be the result returned by Basic.series().

as_numer_denom()

a/b -> a,b

This is just a stub that should be defined by an object’s class methods to get anything else.

as_ordered_factors(order=None)

Transform an expression to 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_ordered_terms(order=None, data=False)

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_poly(*gens, **args)

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
as_powers_dict()
as_real_imag(deep=True)

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()
(-im(w) + re(z), im(z) + re(w))
as_terms()

Transform an expression to a list of terms.

assumptions0

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.

Example:

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'imaginary': False,
'negative': False, 'nonnegative': True, 'nonpositive': False,
'nonzero': True, 'positive': True, 'real': True, 'zero': False}
atoms(*types)

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 I, pi, sin
>>> from sympy.abc import x, y
>>> (1 + x + 2*sin(y + I*pi)).atoms()
set([1, 2, I, pi, x, y])

If one or more types are given, the results will contain only those types of atoms.

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
>>> (1 + x + 2*sin(y + I*pi)).atoms(Function)
set([sin(y + I*pi)])
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
set([I*pi, 2*sin(y + I*pi)])
cancel(*gens, **args)

See the cancel function in sympy.polys

classmethod canonize(*args, **kwargs)
classmethod class_key()
coeff(x, right=False)

Returns the coefficient of the exact term “x” or None if there is no “x”.

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.

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)

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)
>>> (z*(x+y)**2).coeff((x+y)**2)
z
>>> (z*(x+y)**2).coeff(x+y)

In addition, no factoring is done, so 2 + y is not obtained from the following:

>>> (2*x+2+(x+1)*y).coeff(x+1)
y
>>> 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 None is returned:

>>> (n*m + m*n).coeff(n)

If there is only one possible coefficient, it is returned:

>>> (n*m + o*m*n).coeff(m*n)
o
>>> (n*m + o*m*n).coeff(m*n, right=1)
1
collect(syms, evaluate=True, exact=False)

See the collect function in sympy.simplify

combsimp()

See the combsimp function in sympy.simplify

compare(other)

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.

Example:

>>> from sympy.abc import x, y
>>> x.compare(y)
-1
>>> x.compare(x)
0
>>> y.compare(x)
1
static compare_pretty(a, b)

Is a > b in the sense of ordering in printing?

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.

Example:

>>> 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
compute_leading_term(x, skip_abs=False, logx=None)

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.)

conjugate()
could_extract_minus_sign()

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(query)

Count the number of matching subexpressions.

count_ops(visual=None)

wrapper for count_ops that returns the operation count.

default_assumptions = {}
diff(*symbols, **assumptions)
doit(**hints)

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)

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
classmethod eval(z, a=1)
evalf(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)

Expand an expression using hints.

See the docstring in function.expand for more information.

extract_additively(c)

Return None if it’s not possible to make self in the form something + c in a nice way, i.e. preserving the properties of arguments of self.

>>> from sympy import symbols
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_additively(1)
>>> (x+1).extract_additively(x)
1
>>> (x+1).extract_additively(2*x)
>>> (x+1).extract_additively(-x)
2*x + 1
>>> (-x+1).extract_additively(2*x)
-3*x + 1
extract_multiplicatively(c)

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)

See the factor() function in sympy.polys.polytools

fdiff(argindex=1)
find(query, group=False)

Find all subexpressions matching a query.

free_symbols

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)

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.

Example:

>>> from sympy import Tuple
>>> Tuple.fromiter(i for i in xrange(5))
(0, 1, 2, 3, 4)
func
getO()

Returns the additive O(..) symbol if there is one, else None.

getn()

Returns the order of the expression.

The order is determined either from the O(...) term. If there is no O(...) term, it returns None.

Example:

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
has(*args, **kw_args)

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
integrate(*args, **kwargs)

See the integrate function in sympy.integrals

invert(g)

See the invert function in sympy.polys

is_Add = False
is_AlgebraicNumber = False
is_Atom = False
is_Boolean = False
is_Derivative = False
is_Dummy = False
is_Equality = False
is_Float = False
is_Function = True
is_Integer = False
is_Mul = False
is_Not = False
is_Number = False
is_NumberSymbol = False
is_Order = False
is_Piecewise = False
is_Poly = False
is_Pow = False
is_Rational = False
is_Real

Deprecated alias for is_Float

is_Relational = False
is_Symbol = False
is_Wild = False
is_bounded
is_commutative
is_comparable
is_complex
is_composite
is_even
is_finite
is_hypergeometric(k)
is_imaginary
is_infinitesimal
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_number

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_odd
is_polynomial(*syms)

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

See also .is_rational_function()

is_positive
is_prime
is_rational
is_rational_function(*syms)

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).

Example:

>>> 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

See also is_rational_function().

is_real
is_unbounded
is_zero
iter_basic_args()

Iterates arguments of ‘self’.

Example:

>>> from sympy.abc import x
>>> a = 2*x
>>> a.iter_basic_args()
<tupleiterator object at 0x...>
>>> list(a.iter_basic_args())
[2, x]
leadterm(x)

Returns the leading term a*x**b as a tuple (a, b).

Example:

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)

Note:

self is assumed to be the result returned by Basic.series().

limit(x, xlim, dir='+')

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+')

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.

See also nseries().

match(pattern)

Pattern matching.

Wild symbols match all.

Return None when expression (self) does not match with pattern. Otherwise return a dictionary such that:

pattern.subs(self.match(pattern)) == self

Example:

>>> 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).subs(e.match(p*q**r))
4*x**2
matches(expr, repl_dict={}, evaluate=False)

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}
n(n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)

Evaluate the given formula to an accuracy of n digits. Optional keyword arguments:

subs=<dict>
Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits (default=100)
chop=<bool>
Replace tiny real or imaginary parts in subresults by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate to full accuracy, given the available maxprec (default=False)
quad=<str>
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try quad=’osc’.
verbose=<bool>
Print debug information (default=False)
nargs = (1, 2)
normal()
nseries(x=None, x0=0, n=6, dir='+', logx=None)

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.

See also lseries().

nsimplify(constants=[], tolerance=None, full=False)

See the nsimplify function in sympy.simplify

powsimp(deep=False, combine='all')

See the powsimp function in sympy.simplify

radsimp()

See the radsimp function in sympy.simplify

ratsimp()

See the ratsimp function in sympy.simplify

refine(assumption=True)

See the refine function in sympy.assumptions

removeO()

Removes the additive O(..) symbol if there is one

replace(query, value, map=False)

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:

1.1. type -> type
obj.replace(sin, tan)
1.2. type -> func
obj.replace(sin, lambda expr, arg: ...)
2.1. expr -> expr
obj.replace(sin(a), tan(a))
2.2. expr -> func
obj.replace(sin(a), lambda a: ...)
3.1. func -> func
obj.replace(lambda expr: ..., lambda expr: ...)

Examples:

>>> from sympy import log, sin, cos, tan, Wild
>>> from sympy.abc import x
>>> f = log(sin(x)) + tan(sin(x**2))
>>> f.replace(sin, cos)
log(cos(x)) + tan(cos(x**2))
>>> f.replace(sin, lambda arg: sin(2*arg))
log(sin(2*x)) + tan(sin(2*x**2))
>>> sin(x).replace(sin, cos, map=True)
(cos(x), {sin(x): cos(x)})
>>> a = Wild('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))
>>> g = 2*sin(x**3)
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
4*sin(x**9)
rewrite(*args, **hints)

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
separate(deep=False, force=False)

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+')

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

the following is returned instead:

-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()

See the simplify function in sympy.simplify

sort_key(order=None)
subs(*args)

Substitutes an expression.

Calls either _subs_old_new, _subs_dict or _subs_list depending if you give it two arguments (old, new), a dictionary or a list.

Examples:

>>> from sympy import pi
>>> 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
>>> (x + y).subs([(y,x**2), (x,2)])
6
>>> (x + y).subs([(x,2), (y,x**2)])
x**2 + 2
classmethod taylor_term(n, x, *previous_terms)

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”.

together(*args, **kwargs)

See the together function in sympy.polys

trigsimp(deep=False, recursive=False)

See the trigsimp function in sympy.simplify

Functions

esys.escript.symbolic.functions.Eijk(*args, **kwargs)

Represent the Levi-Civita symbol.

This is just compatibility wrapper to LeviCivita().

esys.escript.symbolic.functions.Ylm(l, m, theta, phi)

Spherical harmonics Ylm.

Examples:

>>> from sympy import symbols, Ylm
>>> theta, phi = symbols("theta phi")
>>> Ylm(0, 0, theta, phi)
1/(2*pi**(1/2))
>>> Ylm(1, -1, theta, phi)
6**(1/2)*exp(-I*phi)*sin(theta)/(4*pi**(1/2))
>>> Ylm(1, 0, theta, phi)
3**(1/2)*cos(theta)/(2*pi**(1/2))
esys.escript.symbolic.functions.Zlm(l, m, th, ph)

Real spherical harmonics.

esys.escript.symbolic.functions.bspline_basis(d, knots, n, x, close=True)

The n-th B-spline at x of degree d with knots.

B-Splines are piecewise polynomials of degree d [1]. They are defined on a set of knots, which is a sequence of integers or floats.

The 0th degree splines have a value of one on a single interval:

>>> from sympy import bspline_basis
>>> from sympy.abc import x
>>> d = 0
>>> knots = range(5)
>>> bspline_basis(d, knots, 0, x)
Piecewise((1, [0, 1]), (0, True))

For a given (d, knots) there are len(knots)-d-1 B-splines defined, that are indexed by n (starting at 0).

Here is an example of a cubic B-spline:

>>> bspline_basis(3, range(5), 0, x)
Piecewise((x**3/6, [0, 1)), (-x**3/2 + 2*x**2 - 2*x + 2/3, [1, 2)), (x**3/2 - 4*x**2 + 10*x - 22/3, [2, 3)), (-x**3/6 + 2*x**2 - 8*x + 32/3, [3, 4]), (0, True))

By repeating knot points, you can introduce discontinuities in the B-splines and their derivatives:

>>> d = 1
>>> knots = [0,0,2,3,4]
>>> bspline_basis(d, knots, 0, x)
Piecewise((-x/2 + 1, [0, 2]), (0, True))

It is quite time consuming to construct and evaluate B-splines. If you need to evaluate a B-splines many times, it is best to lambdify them first:

>>> from sympy import lambdify
>>> d = 3
>>> knots = range(10)
>>> b0 = bspline_basis(d, knots, 0, x)
>>> f = lambdify(x, b0)
>>> y = f(0.5)

[1] http://en.wikipedia.org/wiki/B-spline

esys.escript.symbolic.functions.bspline_basis_set(d, knots, x)

Return the len(knots)-d-1 B-splines at x of degree d with knots.

This function returns a list of Piecewise polynomials that are the len(knots)-d-1 B-splines of degree d for the given knots. This function calls bspline_basis(d, knots, n, x) for different values of n.

>>> from sympy import bspline_basis_set
>>> from sympy.abc import x
>>> d = 2
>>> knots = range(5)
>>> splines = bspline_basis_set(d, knots, x)
>>> splines
[Piecewise((x**2/2, [0, 1)), (-x**2 + 3*x - 3/2, [1, 2)), (x**2/2 - 3*x + 9/2, [2, 3]), (0, True)), Piecewise((x**2/2 - x + 1/2, [1, 2)), (-x**2 + 5*x - 11/2, [2, 3)), (x**2/2 - 4*x + 8, [3, 4]), (0, True))]
esys.escript.symbolic.functions.digamma(x)
esys.escript.symbolic.functions.jn_zeros(n, k, method='sympy')

Zeros of the spherical Bessel function of the first kind.

This returns an array of zeros of jn up to the k-th zero.

method = “sympy”: uses the SymPy’s jn and findroot to find all roots method = “scipy”: uses the SciPy’s sph_jn and newton to find all roots,

which if faster than method=”sympy”, but it requires SciPy and only works with low precision floating point numbers

Examples

>>> from sympy.mpmath import nprint
>>> from sympy import jn_zeros
>>> nprint(jn_zeros(2, 4))
[5.76345919689, 9.09501133048, 12.3229409706, 15.5146030109]
esys.escript.symbolic.functions.laguerre_l(n, alpha, x)

Returns the generalized Laguerre polynomial.

n : int
Degree of Laguerre polynomial. Must be n >= 0.
alpha : Expr
Arbitrary expression. For alpha=0 regular Laguerre polynomials will be generated.

Examples

To construct generalized Laguerre polynomials issue:

>>> from sympy import laguerre_l, var
>>> var("alpha, x")
(alpha, x)

>>> laguerre_l(0, alpha, x)
1
>>> laguerre_l(1, alpha, x)
alpha - x + 1
>>> laguerre_l(2, alpha, x)
alpha**2/2 + 3*alpha/2 + x**2/2 + x*(-alpha - 2) + 1

If you set alpha=0, you get regular Laguerre polynomials:

>>> laguerre_l(1, 0, x)
-x + 1
>>> laguerre_l(2, 0, x)
x**2/2 - 2*x + 1
>>> laguerre_l(3, 0, x)
-x**3/6 + 3*x**2/2 - 3*x + 1
>>> laguerre_l(4, 0, x)
x**4/24 - 2*x**3/3 + 3*x**2 - 4*x + 1
esys.escript.symbolic.functions.piecewise_fold(expr)

Takes an expression containing a piecewise function and returns the expression in piecewise form.

>>> from sympy import Piecewise, piecewise_fold
>>> from sympy.abc import x
>>> p = Piecewise((x, x < 1), (1, 1 <= x))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, 1 <= x))
esys.escript.symbolic.functions.sqrt(arg)
esys.escript.symbolic.functions.trigamma(x)

Others

  • Id
  • S
  • __author__
  • __builtins__
  • __copyright__
  • __doc__
  • __file__
  • __license__
  • __name__
  • __package__
  • __url__