Converts an arbitrary expression to a type that can be used inside sympy.
For example, it will convert python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE.
If the argument is already a type that sympy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type.
>>> from sympy import sympify
>>> sympify(2).is_integer
True
>>> sympify(2).is_real
True
>>> sympify(2.0).is_real
True
>>> sympify("2.0").is_real
True
>>> sympify("2e-45").is_real
True
If the expression could not be converted, a SympifyError is raised.
>>> sympify("x***2")
Traceback (most recent call last):
...
SympifyError: SympifyError: "could not parse u'x***2'"
If the option strict is set to True, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.
>>> sympify(True)
True
>>> sympify(True, strict=True)
Traceback (most recent call last):
...
SympifyError: SympifyError: True
To extend \(sympify\) to convert custom objects (not derived from \(Basic\)), the static dictionary \(convert\) is provided. The custom converters are usually added at import time, and will apply to all objects of the given class or its derived classes.
For example, all geometry objects derive from \(GeometryEntity\) class, and should not be altered by the converter, so we add the following after defining that class:
>>> from sympy.core.sympify import converter
>>> from sympy.geometry.entity import GeometryEntity
>>> converter[GeometryEntity] = lambda x: x
caching decorator.
important: the result of cached function must be immutable
Example
>>> from sympy.core.cache import cacheit
>>> @cacheit
... def f(a,b):
... return a+b
>>> @cacheit
... def f(a,b):
... return [a,b] # <-- WRONG, returns mutable object
to force cacheit to check returned results mutability and consistency, set environment variable SYMPY_USE_CACHE to ‘debug’
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,)
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).
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
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}
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)])
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
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
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)
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
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.
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)
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
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
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
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]
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
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 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:
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)
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
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]
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
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]]
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.
>>> 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, ())
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.
>>> 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, ())
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)
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)
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.:
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:
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))
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().
a/b -> a,b
This is just a stub that should be defined by an object’s class methods to get anything else.
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)]
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]
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))
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
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.)
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
Expand an expression using hints.
See the docstring in function.expand for more information.
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
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
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()
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
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()
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().
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().
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().
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().
See the nsimplify function in sympy.simplify
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).
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
You can override the default assumptions in the constructor:
>>> from sympy import symbols
>>> A,B = symbols('A,B', commutative = False)
>>> bool(A*B != B*A)
True
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
True
Dummy symbols are each unique, identified by an internal count index:
>>> from sympy import Dummy
>>> bool(Dummy("x") == Dummy("x")) == True
False
If a name is not supplied then a string value of the count index will be used. This is useful when a temporary variable is needed and the name of the variable used in the expression is not important.
>>> Dummy._count = 0 # /!\ this should generally not be changed; it is being
>>> Dummy() # used here to make sure that the doctest passes.
_0
Transform strings into instances of Symbol class.
symbols() function returns a sequence of symbols with names taken from names argument, which can be a comma or whitespace delimited string, or a sequence of strings:
>>> from sympy import symbols, Function
>>> x, y, z = symbols('x,y,z')
>>> a, b, c = symbols('a b c')
The type of output is dependent on the properties of input arguments:
>>> symbols('x')
x
>>> symbols('x,')
(x,)
>>> symbols('x,y')
(x, y)
>>> symbols(('a', 'b', 'c'))
(a, b, c)
>>> symbols(['a', 'b', 'c'])
[a, b, c]
>>> symbols(set(['a', 'b', 'c']))
set([a, b, c])
If an iterable container is needed for a single symbol, set the seq argument to True or terminate the symbol name with a comma:
>>> symbols('x', seq=True)
(x,)
To reduce typing, range syntax is supported to create indexed symbols:
>>> symbols('x:10')
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
>>> symbols('x5:10')
(x5, x6, x7, x8, x9)
>>> symbols('x5:10,y:5')
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
>>> symbols(('x5:10', 'y:5'))
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
To reduce typing even more, lexicographic range syntax is supported:
>>> symbols('x:z')
(x, y, z)
>>> symbols('a:d,x:z')
(a, b, c, d, x, y, z)
>>> symbols(('a:d', 'x:z'))
((a, b, c, d), (x, y, z))
All newly created symbols have assumptions set accordingly to args:
>>> a = symbols('a', integer=True)
>>> a.is_integer
True
>>> x, y, z = symbols('x,y,z', real=True)
>>> x.is_real and y.is_real and z.is_real
True
Despite its name, symbols() can create symbol–like objects of other type, for example instances of Function or Wild classes. To achieve this, set cls keyword argument to the desired type:
>>> symbols('f,g,h', cls=Function)
(f, g, h)
>>> type(_[0])
<class 'sympy.core.function.UndefinedFunction'>
Create symbols and inject them into the global namespace.
This calls symbols() with the same arguments and puts the results into the global namespace. It’s recommended not to use var() in library code, where symbols() has to be used:
>>> from sympy import var
>>> var('x')
x
>>> x
x
>>> var('a,ab,abc')
(a, ab, abc)
>>> abc
abc
>>> var('x,y', real=True)
(x, y)
>>> x.is_real and y.is_real
True
See symbol() documentation for more details on what kinds of arguments can be passed to var().
Represents any kind of number in sympy.
Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class.
If you want to represent, for example, 1+sqrt(2), then you need to do:
Rational(1) + sqrt(Rational(2))
Represents a floating point number. It is capable of representing arbitrary-precision floating-point numbers
Usage
Float(3.5)
3.5 # (the 3.5 was converted from a python float)
Float("3.0000000000000005")
>>> from sympy import Float
>>> Float((1,3,0,2)) # mpmath tuple: (-1)**1 * 3 * 2**0; 3 has 2 bits
-3.00000000000000
Notes
Represents integers and rational numbers (p/q) of any size.
Examples
>>> from sympy import Rational
>>> from sympy.abc import x, y
>>> Rational(3)
3
>>> Rational(1,2)
1/2
>>> Rational(1.5)
1
Rational can also accept strings that are valid literals for reals:
>>> Rational("1.23")
123/100
>>> Rational('1e-2')
1/100
>>> Rational(".1")
1/10
Parsing needs for any other type of string for which a Rational is desired can be handled with the rational=True option in sympify() which produces rationals from strings like ‘.[3]’ (=1/3) and ‘3/10’ (=3/10).
Low-level
Access numerator and denominator as .p and .q:
>>> r = Rational(3,4)
>>> r
3/4
>>> r.p
3
>>> r.q
4
Note that p and q return integers (not sympy Integers) so some care is needed when using them in expressions:
>>> r.p/r.q
0
Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
>>> from sympy.abc import x, y
>>> (3*x*y).as_two_terms()
(3, x*y)
Returns the leading term and it’s order.
Examples:
>>> from sympy.abc import x
>>> (x+1+1/x**5).extract_leading_order(x)
((x**(-5), O(x**(-5))),)
>>> (1+x).extract_leading_order(x)
((1, O(1)),)
>>> (x+x**2).extract_leading_order(x)
((x, O(x)),)
Takes the sequence “seq” of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to addition.
Matches Add/Mul “pattern” to an expression “expr”.
This function is the main workhorse for Add/Mul.
For instance:
>>> from sympy import symbols, Wild, sin
>>> a = Wild("a")
>>> b = Wild("b")
>>> c = Wild("c")
>>> x, y, z = symbols("x y z")
>>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
{a_: x, b_: y, c_: z}
In the example above, “a+sin(b)*c” is the pattern, and “x+sin(y)*z” is the expression.
The repl_dict contains parts that were already matched, and the “evaluate=True” kwarg tells _matches_commutative to substitute this repl_dict into pattern. For example here:
>>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x}, evaluate=True)
{a_: x, b_: y, c_: z}
_matches_commutative substitutes “x” for “a” in the pattern and calls itself again with the new pattern “x+b*c” and evaluate=False (default):
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
{a_: x, b_: y, c_: z}
the only function of the repl_dict now is just to return it in the result, e.g. if you omit it:
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
{b_: y, c_: z}
the “a: x” is not returned in the result, but otherwise it is equivalent.
Generalizes a function taking scalars to accept multidimensional arguments.
For example:
(1) @vectorize(0)
def sin(x):
....
sin([1, x, y])
--> [sin(1), sin(x), sin(y)]
(2) @vectorize(0,1)
def diff(f(y), y)
....
diff([f(x,y,z),g(x,y,z),h(x,y,z)], [x,y,z])
--> [[d/dx f, d/dy f, d/dz f], [d/dx g, d/dy g, d/dz g], [d/dx h, d/dy h, d/dz h]]
Lambda(x, expr) represents a lambda function similar to Python’s ‘lambda x: expr’. A function of several variables is written as Lambda((x, y, ...), expr).
A simple example:
>>> from sympy import Lambda
>>> from sympy.abc import x
>>> f = Lambda(x, x**2)
>>> f(4)
16
For multivariate functions, use:
>>> from sympy.abc import y, z, t
>>> f2 = Lambda((x, y, z, t), x + y**z + t**z)
>>> f2(1, 2, 3, 4)
73
A handy shortcut for lots of arguments:
>>> p = x, y, z
>>> f = Lambda(p, x + y*z)
>>> f(*p)
x + y*z
Carries out differentiation of the given expression with respect to symbols.
expr must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the non-trivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative.
If evaluate is set to True and the expression can not be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked.
Examples:
Differentiate f with respect to symbols.
This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x).
You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False.
Examples
>>> from sympy import sin, cos, Function, diff
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> diff(sin(x), x)
cos(x)
>>> diff(f(x), x, x, x)
Derivative(f(x), x, x, x)
>>> diff(f(x), x, 3)
Derivative(f(x), x, x, x)
>>> diff(sin(x)*cos(y), x, 2, y, 2)
sin(x)*cos(y)
>>> type(diff(sin(x), x))
cos
>>> type(diff(sin(x), x, evaluate=False))
<class 'sympy.core.function.Derivative'>
>>> type(diff(sin(x), x, 0))
sin
>>> type(diff(sin(x), x, 0, evaluate=False))
sin
>>> diff(sin(x))
cos(x)
>>> diff(sin(x*y))
Traceback (most recent call last):
...
ValueError: specify differentiation variables to differentiate sin(x*y)
Note that diff(sin(x)) syntax is meant only for convenience in interactive sessions and should be avoided in library code.
See Also http://documents.wolfram.com/v5/Built-inFunctions/AlgebraicComputation/Calculus/D.html
Represents unevaluated substitutions of an expression.
Subs(expr, x, x0) receives 3 arguments: an expression, a variable or list of distinct variables and a point or list of evaluation points corresponding to those variables.
Subs objects are generally useful to represent unevaluated derivatives calculated at a point.
The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity.
There’s no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression.
When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()).
A simple example:
>>> from sympy import Subs, Function, sin
>>> from sympy.abc import x, y, z
>>> f = Function('f')
>>> e = Subs(f(x).diff(x), x, y)
>>> e.subs(y, 0)
Subs(Derivative(f(_x), _x), (_x,), (0,))
>>> e.subs(f, sin).doit()
cos(y)
An example with several variables:
>>> Subs(f(x)*sin(y)+z, (x, y), (0, 1))
Subs(z + f(_x)*sin(_y), (_x, _y), (0, 1))
>>> _.doit()
z + f(0)*sin(1)
Expand an expression using methods given as hints.
Hints are applied with arbitrary order so your code shouldn’t depend on the way hints are passed to this method.
basic is a generic keyword for methods that want to be expanded automatically. For example, Integral uses expand_basic to expand the integrand. If you want your class expand methods to run automatically and they don’t fit one of the already automatic methods, wrap it around _eval_expand_basic.
If deep is set to True, things like arguments of functions are recursively expanded. Use deep=False to only expand on the top level.
If the ‘force’ hint is used, assumptions about variables will be ignored in making the expansion.
Also see expand_log, expand_mul, separate, expand_complex, expand_trig, and expand_func, which are wrappers around those expansion methods.
>>> from sympy import cos, exp
>>> from sympy.abc import x, y, z
mul - Distributes multiplication over addition:
>>> (y*(x + z)).expand(mul=True)
x*y + y*z
complex - Split an expression into real and imaginary parts:
>>> (x + y).expand(complex=True)
I*im(x) + I*im(y) + re(x) + re(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
power_exp - Expand addition in exponents into multiplied bases:
>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y
power_base - Split powers of multiplied bases if assumptions allow or if the ‘force’ hint is used:
>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z
log - Pull out power of an argument as a coefficient and split logs products into sums of logs. Note that these only work if the arguments of the log function have the proper assumptions: the arguments must be positive and the exponents must be real or else the force hint must be True:
>>> from sympy import log, symbols, oo
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)
trig - Do trigonometric expansions:
>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
func - Expand other functions:
>>> from sympy import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)
multinomial - Expand (x + y + ...)**n where n is a positive integer:
>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
You can shut off methods that you don’t want:
>>> (exp(x + y)*(x + y)).expand()
x*exp(x)*exp(y) + y*exp(x)*exp(y)
>>> (exp(x + y)*(x + y)).expand(power_exp=False)
x*exp(x + y) + y*exp(x + y)
>>> (exp(x + y)*(x + y)).expand(mul=False)
(x + y)*exp(x)*exp(y)
Use deep=False to only expand on the top level:
>>> exp(x + exp(x + y)).expand()
exp(x)*exp(exp(x)*exp(y))
>>> exp(x + exp(x + y)).expand(deep=False)
exp(x)*exp(exp(x + y))
Note: because hints are applied in arbitrary order, some hints may prevent expansion by other hints if they are applied first. In particular, mul may distribute multiplications and prevent log and power_base from expanding them. Also, if mul is applied before multinomial, the expression might not be fully distributed. The solution is to expand with mul=False first, then run expand_mul if you need further expansion.
Examples:
>>> from sympy import expand_log, expand, expand_mul
>>> x, y, z = symbols('x,y,z', positive=True)
expand(log(x*(y + z))) # could be either one below
log(x*y + x*z)
log(x) + log(y + z)
>>> expand_log(log(x*y + x*z))
log(x*y + x*z)
>>> expand(log(x*(y + z)), mul=False)
log(x) + log(y + z)
expand((x*(y + z))**x) # could be either one below
(x*y + x*z)**x
x**x*(y + z)**x
>>> expand((x*(y + z))**x, mul=False)
x**x*(y + z)**x
expand(x*(y + z)**2) # could be either one below
2*x*y*z + x*y**2 + x*z**2
x*(y + z)**2
>>> expand(x*(y + z)**2, mul=False)
x*(y**2 + 2*y*z + z**2)
>>> expand_mul(_)
x*y**2 + 2*x*y*z + x*z**2
Return a representation (integer or expression) of the operations in expr.
If visual is False (default) then the sum of the coefficients of the visual expression will be returned.
If visual is True then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur.
If expr is an iterable, the sum of the op counts of the items will be returned.
Examples:
>>> from sympy.abc import a, b, x, y
>>> from sympy import sin, count_ops
Although there isn’t a SUB object, minus signs are interpreted as either negations or subtractions:
>>> (x - y).count_ops(visual=True)
SUB
>>> (-x).count_ops(visual=True)
NEG
Here, there are two Adds and a Pow:
>>> (1 + a + b**2).count_ops(visual=True)
2*ADD + POW
In the following, an Add, Mul, Pow and two functions:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=True)
ADD + MUL + POW + 2*SIN
for a total of 5:
>>> (sin(x)*x + sin(x)**2).count_ops(visual=False)
5
Note that “what you type” is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs:
>>> (1/x/y).count_ops(visual=True)
DIV + MUL
The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial:
>>> eq=x*(1 + x*(2 + x*(3 + x)))
>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True)
-MUL + 3*POW
The count_ops function also handles iterables:
>>> count_ops([x, sin(x), None, True, x + 2], visual=False)
2
>>> count_ops([x, sin(x), None, True, x + 2], visual=True)
ADD + SIN
>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True)
2*ADD + SIN
Wrapper around expand that only uses the mul hint. See the expand docstring for more information.
Example:
>>> from sympy import symbols, expand_mul, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2))
x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
Wrapper around expand that only uses the log hint. See the expand docstring for more information.
Example:
>>> from sympy import symbols, expand_log, exp, log
>>> x, y = symbols('x,y', positive=True)
>>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
(x + y)*(log(x) + 2*log(y))*exp(x + y)
Wrapper around expand that only uses the trig hint. See the expand docstring for more information.
Example:
>>> from sympy import expand_trig, sin, cos
>>> from sympy.abc import x, y
>>> expand_trig(sin(x+y)*(x+y))
(x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
Wrapper around expand that only uses the complex hint. See the expand docstring for more information.
Example:
>>> from sympy import expand_complex, I, im, re
>>> from sympy.abc import z
>>> expand_complex(z**(2*I))
I*im(z**(2*I)) + re(z**(2*I))
Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information.
Example:
>>> from sympy import symbols, expand_multinomial, exp
>>> x, y = symbols('x y', positive=True)
>>> expand_multinomial((x + exp(x + 1))**2)
x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
Represents any kind of set.
Real intervals are represented by the Interval class and unions of sets by the Union class. The empty set is represented by the EmptySet class and available as a singleton as S.EmptySet.
The complement of ‘self’.
As a shortcut it is possible to use the ‘~’ or ‘-‘ operators:
>>> from sympy import Interval
>>> Interval(0, 1).complement
(-oo, 0) U (1, oo)
>>> ~Interval(0, 1)
(-oo, 0) U (1, oo)
>>> -Interval(0, 1)
(-oo, 0) U (1, oo)
Returns True if ‘other’ is contained in ‘self’ as an element.
As a shortcut it is possible to use the ‘in’ operator:
>>> from sympy import Interval
>>> Interval(0, 1).contains(0.5)
True
>>> 0.5 in Interval(0, 1)
True
The infimum of ‘self’.
>>> from sympy import Interval, Union
>>> Interval(0, 1).inf
0
>>> Union(Interval(0, 1), Interval(2, 3)).inf
0
Returns the intersection of ‘self’ and ‘other’.
>>> from sympy import Interval
>>> Interval(1, 3).intersect(Interval(1, 2))
[1, 2]
The (Lebesgue) measure of ‘self’.
>>> from sympy import Interval, Union
>>> Interval(0, 1).measure
1
>>> Union(Interval(0, 1), Interval(2, 3)).measure
2
Returns True if ‘other’ is a subset of ‘self’.
>>> from sympy import Interval
>>> Interval(0, 1).contains(0)
True
>>> Interval(0, 1, left_open=True).contains(0)
False
The supremum of ‘self’.
>>> from sympy import Interval, Union
>>> Interval(0, 1).sup
1
>>> Union(Interval(0, 1), Interval(2, 3)).sup
3
Returns the union of ‘self’ and ‘other’. As a shortcut it is possible to use the ‘+’ operator:
>>> from sympy import Interval, FiniteSet
>>> Interval(0, 1).union(Interval(2, 3))
[0, 1] U [2, 3]
>>> Interval(0, 1) + Interval(2, 3)
[0, 1] U [2, 3]
>>> Interval(1, 2, True, True) + FiniteSet(2, 3)
(1, 2] U {3}
Similarly it is possible to use the ‘-‘ operator for set differences:
>>> Interval(0, 2) - Interval(0, 1)
(1, 2]
>>> Interval(1, 3) - FiniteSet(2)
[1, 2) U (2, 3]
Represents a real interval as a Set.
Returns an interval with end points “start” and “end”.
For left_open=True (default left_open is False) the interval will be open on the left. Similarly, for right_open=True the interval will be open on the right.
>>> from sympy import Symbol, Interval, sets
>>> Interval(0, 1)
[0, 1]
>>> Interval(0, 1, False, True)
[0, 1)
>>> a = Symbol('a', real=True)
>>> Interval(0, a)
[0, a]
The right end point of ‘self’. This property takes the same value as the ‘sup’ property.
>>> from sympy import Interval
>>> Interval(0, 1).end
1
The left end point of ‘self’. This property takes the same value as the ‘inf’ property.
>>> from sympy import Interval
>>> Interval(0, 1).start
0
True if ‘self’ is left-open.
>>> from sympy import Interval
>>> Interval(0, 1, left_open=True).left_open
True
>>> Interval(0, 1, left_open=False).left_open
False
The right end point of ‘self’. This property takes the same value as the ‘sup’ property.
>>> from sympy import Interval
>>> Interval(0, 1).end
1
Represents a union of sets as a Set.
>>> from sympy import Union, Interval
>>> Union(Interval(1, 2), Interval(3, 4))
[1, 2] U [3, 4]
The Union constructor will always try to merge overlapping intervals, if possible. For example:
>>> Union(Interval(1, 2), Interval(2, 3))
[1, 3]
Calls x.evalf(n, **options).
Both .evalf() and N() are equivalent, use the one that you like better. See also the docstring of .evalf() for information on the options.
Example:
>>> from sympy import Sum, Symbol, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(Sum(1/k**k, (k, 1, oo)), 4)
1.291
Wrapper around the builtin tuple object
The Tuple is a subclass of Basic, so that it works well in the Sympy framework. The wrapped tuple is available as self.args, but you can also access elements or slices with [:] syntax.
>>> from sympy import symbols
>>> from sympy.core.containers import Tuple
>>> a, b, c, d = symbols('a b c d')
>>> Tuple(a, b, c)[1:]
(b, c)
>>> Tuple(a, b, c).subs(a, d)
(d, b, c)