Core¶
sympify¶
- sympy.core.sympify.sympify(
- a: int,
- *,
- strict: bool = False,
- sympy.core.sympify.sympify(
- a: float,
- *,
- strict: bool = False,
- sympy.core.sympify.sympify(
- a: Expr | complex,
- *,
- strict: bool = False,
- sympy.core.sympify.sympify(
- a: Tbasic,
- *,
- strict: bool = False,
- sympy.core.sympify.sympify(
- a: Any,
- *,
- strict: bool = False,
Converts an arbitrary expression to a type that can be used inside SymPy.
- Parameters:
a :
any object defined in SymPy
standard numeric Python types:
int
,long
,float
,Decimal
strings (like
"0.09"
,"2e-19"
or'sin(x)'
)booleans, including
None
(will leaveNone
unchanged)dicts, lists, sets or tuples containing any of the above
convert_xor : bool, optional
If true, treats
^
as exponentiation. If False, treats^
as XOR itself. Used only when input is a string.locals : any object defined in SymPy, optional
In order to have strings be recognized it can be imported into a namespace dictionary and passed as locals.
strict : bool, optional
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.rational : bool, optional
If
True
, converts floats intoRational
. IfFalse
, it lets floats remain as it is. Used only when input is a string.evaluate : bool, optional
If False, then arithmetic and operators will be converted into their SymPy equivalents. If True the expression will be evaluated and the result will be returned.
Explanation
It will convert Python ints into instances of
Integer
, floats into instances ofFloat
, etc. It is also able to coerce symbolic expressions which inherit fromBasic
. This can be useful in cooperation with SAGE.Warning
Note that this function uses
eval
, and thus shouldn’t be used on unsanitized input.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.
Examples
>>> 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 'x***2'"
When attempting to parse non-Python syntax using
sympify
, it raises aSympifyError
:>>> sympify("2x+1") Traceback (most recent call last): ... SympifyError: Sympify of expression 'could not parse '2x+1'' failed
To parse non-Python syntax, use
parse_expr
fromsympy.parsing.sympy_parser
.>>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("2x+1", transformations="all") 2*x + 1
For more details about
transformations
: seeparse_expr()
Locals
The sympification happens with access to everything that is loaded by
from sympy import *
; anything used in a string that is not defined by that import will be converted to a symbol. In the following, thebitcount
function is treated as a symbol and theO
is interpreted as theOrder
object (used with series) and it raises an error when used improperly:>>> s = 'bitcount(42)' >>> sympify(s) bitcount(42) >>> sympify("O(x)") O(x) >>> sympify("O + 1") Traceback (most recent call last): ... TypeError: unbound method...
In order to have
bitcount
be recognized it can be imported into a namespace dictionary and passed as locals:>>> ns = {} >>> exec('from sympy.core.evalf import bitcount', ns) >>> sympify(s, locals=ns) 6
In order to have the
O
interpreted as a Symbol, identify it as such in the namespace dictionary. This can be done in a variety of ways; all three of the following are possibilities:>>> from sympy import Symbol >>> ns["O"] = Symbol("O") # method 1 >>> exec('from sympy.abc import O', ns) # method 2 >>> ns.update(dict(O=Symbol("O"))) # method 3 >>> sympify("O + 1", locals=ns) O + 1
If you want all single-letter and Greek-letter variables to be symbols then you can use the clashing-symbols dictionaries that have been defined there as private variables:
_clash1
(single-letter variables),_clash2
(the multi-letter Greek names) or_clash
(both single and multi-letter names that are defined inabc
).>>> from sympy.abc import _clash1 >>> set(_clash1) # if this fails, see issue #23903 {'E', 'I', 'N', 'O', 'Q', 'S'} >>> sympify('I & Q', _clash1) I & Q
Strict
If the option
strict
is set toTrue
, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised.>>> print(sympify(None)) None >>> sympify(None, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: None
Deprecated since version 1.6:
sympify(obj)
automatically falls back tostr(obj)
when all other conversion methods fail, but this is deprecated.strict=True
will disable this deprecated behavior. See The string fallback in sympify().Evaluation
If the option
evaluate
is set toFalse
, then arithmetic and operators will be converted into their SymPy equivalents and theevaluate=False
option will be added. NestedAdd
orMul
will be denested first. This is done via an AST transformation that replaces operators with their SymPy equivalents, so if an operand redefines any of those operations, the redefined operators will not be used. If argument a is not a string, the mathematical expression is evaluated before being passed to sympify, so addingevaluate=False
will still return the evaluated result of expression.>>> sympify('2**2 / 3 + 5') 19/3 >>> sympify('2**2 / 3 + 5', evaluate=False) 2**2/3 + 5 >>> sympify('4/2+7', evaluate=True) 9 >>> sympify('4/2+7', evaluate=False) 4/2 + 7 >>> sympify(4/2+7, evaluate=False) 9.00000000000000
Extending
To extend
sympify
to convert custom objects (not derived fromBasic
), just define a_sympy_
method to your class. You can do that even to classes that you do not own by subclassing or adding the method at runtime.>>> from sympy import Matrix >>> class MyList1(object): ... def __iter__(self): ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] ... def _sympy_(self): return Matrix(self) >>> sympify(MyList1()) Matrix([ [1], [2]])
If you do not have control over the class definition you could also use the
converter
global dictionary. The key is the class and the value is a function that takes a single argument and returns the desired SymPy object, e.g.converter[MyList] = lambda x: Matrix(x)
.>>> class MyList2(object): # XXX Do not do this if you control the class! ... def __iter__(self): # Use _sympy_! ... yield 1 ... yield 2 ... return ... def __getitem__(self, i): return list(self)[i] >>> from sympy.core.sympify import converter >>> converter[MyList2] = lambda x: Matrix(x) >>> sympify(MyList2()) Matrix([ [1], [2]])
Notes
The keywords
rational
andconvert_xor
are only used when the input is a string.Convert_xor
>>> sympify('x^y',convert_xor=True) x**y >>> sympify('x^y',convert_xor=False) x ^ y
Rational
>>> sympify('0.1',rational=False) 0.1 >>> sympify('0.1',rational=True) 1/10
Sometimes autosimplification during sympification results in expressions that are very different in structure than what was entered. Until such autosimplification is no longer done, the
kernS
function might be of some use. In the example below you can see how an expression reduces to \(-1\) by autosimplification, but does not do so whenkernS
is used.>>> from sympy.core.sympify import kernS >>> from sympy.abc import x >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1 -1 >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1' >>> sympify(s) -1 >>> kernS(s) -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
- class sympy.core.sympify.Tbasic¶
assumptions¶
This module contains the machinery handling assumptions. Do also consider the guide Assumptions.
All symbolic objects have assumption attributes that can be accessed via
.is_<assumption name>
attribute.
Assumptions determine certain properties of symbolic objects and can
have 3 possible values: True
, False
, None
. True
is returned if the
object has the property and False
is returned if it does not or cannot
(i.e. does not make sense):
>>> from sympy import I
>>> I.is_algebraic
True
>>> I.is_real
False
>>> I.is_prime
False
When the property cannot be determined (or when a method is not
implemented) None
will be returned. For example, a generic symbol, x
,
may or may not be positive so a value of None
is returned for x.is_positive
.
By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc.
Here follows a list of possible assumption names:
- commutative¶
object commutes with any other object with respect to multiplication operation. See [12].
- complex¶
object can have only values from the set of complex numbers. See [13].
- imaginary¶
object value is a number that can be written as a real number multiplied by the imaginary unit
I
. See [R112]. Please note that0
is not considered to be an imaginary number, see issue #7649.- real¶
object can have only values from the set of real numbers.
- extended_real¶
object can have only values from the set of real numbers,
oo
and-oo
.- integer¶
object can have only values from the set of integers.
- odd¶
- even¶
object can have only values from the set of odd (even) integers [R111].
- prime¶
object is a natural number greater than 1 that has no positive divisors other than 1 and itself. See [R115].
- composite¶
object is a positive integer that has at least one positive divisor other than 1 or the number itself. See [R113].
- zero¶
object has the value of 0.
- nonzero¶
object is a real number that is not zero.
- rational¶
object can have only values from the set of rationals.
- algebraic¶
object can have only values from the set of algebraic numbers [11].
- transcendental¶
object can have only values from the set of transcendental numbers [10].
- irrational¶
object value cannot be represented exactly by
Rational
, see [R114].- finite¶
- infinite¶
object absolute value is bounded (arbitrarily large). See [R116], [R117], [R118].
- negative¶
- nonnegative¶
object can have only negative (nonnegative) values [R110].
- positive¶
- nonpositive¶
object can have only positive (nonpositive) values.
- extended_negative¶
- extended_nonnegative¶
- extended_positive¶
- extended_nonpositive¶
- extended_nonzero¶
as without the extended part, but also including infinity with corresponding sign, e.g., extended_positive includes
oo
- hermitian¶
- antihermitian¶
object belongs to the field of Hermitian (antihermitian) operators.
Examples¶
>>> from sympy import Symbol
>>> x = Symbol('x', real=True); x
x
>>> x.is_real
True
>>> x.is_complex
True
See Also¶
Notes¶
The fully-resolved assumptions for any SymPy expression can be obtained as follows:
>>> from sympy.core.assumptions import assumptions
>>> x = Symbol('x',positive=True)
>>> assumptions(x + I)
{'commutative': True, 'complex': True, 'composite': False, 'even':
False, 'extended_negative': False, 'extended_nonnegative': False,
'extended_nonpositive': False, 'extended_nonzero': False,
'extended_positive': False, 'extended_real': False, 'finite': True,
'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
False, 'negative': False, 'noninteger': False, 'nonnegative': False,
'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
False, 'prime': False, 'rational': False, 'real': False, 'zero':
False}
Developers Notes¶
The current (and possibly incomplete) values are stored
in the obj._assumptions dictionary
; queries to getter methods
(with property decorators) or attributes of objects/classes
will return values and update the dictionary.
>>> eq = x**2 + I
>>> eq._assumptions
{}
>>> eq.is_finite
True
>>> eq._assumptions
{'finite': True, 'infinite': False}
For a Symbol
, there are two locations for assumptions that may
be of interest. The assumptions0
attribute gives the full set of
assumptions derived from a given set of initial assumptions. The
latter assumptions are stored as Symbol._assumptions_orig
>>> Symbol('x', prime=True, even=True)._assumptions_orig
{'even': True, 'prime': True}
The _assumptions_orig
are not necessarily canonical nor are they filtered
in any way: they records the assumptions used to instantiate a Symbol and (for
storage purposes) represent a more compact representation of the assumptions
needed to recreate the full set in Symbol.assumptions0
.
References¶
cache¶
- sympy.core.cache.__cacheit(maxsize)[source]¶
caching decorator.
important: the result of cached function must be immutable
Examples
>>> from sympy import cacheit >>> @cacheit ... def f(a, b): ... return a+b
>>> @cacheit ... def f(a, b): # noqa: F811 ... return [a, b] # <-- WRONG, returns mutable object
to force cacheit to check returned results mutability and consistency, set environment variable SYMPY_USE_CACHE to ‘debug’
basic¶
- class collections.abc.Mapping¶
- class collections.abc.Iterable¶
- class sympy.core.basic.Basic(*args)[source]¶
Base class for all SymPy objects.
Notes And Conventions
Always use
.args
, when accessing parameters of some instance:
>>> from sympy import 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
Never use internal methods or variables (the ones prefixed with
_
):
>>> cot(x)._args # do not use this, use cot(x).args instead (x,)
By “SymPy object” we mean something that can be returned by
sympify
. But not all objects one encounters using SymPy are subclasses of Basic. For example, mutable objects are not:>>> from sympy import Basic, Matrix, sympify >>> A = Matrix([[1, 2], [3, 4]]).as_mutable() >>> isinstance(A, Basic) False
>>> B = sympify(A) >>> isinstance(B, Basic) True
- property args: tuple[Basic, ...]¶
Returns a tuple of arguments of ‘self’.
Examples
>>> from sympy import 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
Notes
Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Do not override .args() from Basic (so that it is easy to change the interface in the future if needed).
- as_content_primitive(
- radical=False,
- clear=True,
A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression.
- as_dummy() Self [source]¶
Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True. When applied to a symbol a new symbol having only the same commutativity will be returned.
Examples
>>> from sympy import Integral, Symbol >>> from sympy.abc import x >>> r = Symbol('r', real=True) >>> Integral(r, (r, x)).as_dummy() Integral(_0, (_0, x)) >>> _.variables[0].is_real is None True >>> r.as_dummy() _r
Notes
Any object that has structurally bound variables should have a property,
bound_symbols
that returns those symbols appearing in the object.
- property 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.
Examples
>>> from sympy import Symbol >>> from sympy.abc import x >>> x.assumptions0 {'commutative': True} >>> x = Symbol("x", positive=True) >>> x.assumptions0 {'commutative': True, 'complex': True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False}
- atoms() set[Basic] [source]¶
- atoms( ) set[Tbasic]
Returns the atoms that form the current object.
By default, only objects that are truly atomic and cannot 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() {1, 2, I, pi, x, y}
If one or more types are given, the results will contain only those types of atoms.
>>> from sympy import Number, NumberSymbol, Symbol >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol) {x, y}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number) {1, 2}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol) {1, 2, pi}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I) {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 {x, y}
Be careful to check your assumptions when using the implicit option since
S(1).is_Integer = True
buttype(S(1))
isOne
, a special type of SymPy atom, whiletype(S(2))
is typeInteger
and will find all integers in an expression:>>> from sympy import S >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1)) {1}
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2)) {1, 2}
Finally, arguments to atoms() can select more than atomic atoms: any SymPy type (loaded in core/__init__.py) can be listed as an argument and those types of “atoms” as found in scanning the arguments of the expression recursively:
>>> from sympy import Function, Mul >>> from sympy.core.function import AppliedUndef >>> f = Function('f') >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function) {f(x), sin(y + I*pi)} >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) {f(x)}
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) {I*pi, 2*sin(y + I*pi)}
- property canonical_variables: dict[Basic, Symbol]¶
Return a dictionary mapping any variable defined in
self.bound_symbols
to Symbols that do not clash with any free symbols in the expression.Examples
>>> from sympy import Lambda >>> from sympy.abc import x >>> Lambda(x, 2*x).canonical_variables {x: _0}
- compare(other)[source]¶
Return -1, 0, 1 if the object is less than, equal, or greater than other in a canonical sense. Non-Basic are always greater than Basic. If both names of the classes being compared appear in the \(ordering_of_classes\) then the ordering will depend on the appearance of the names there. If either does not appear in that list, then the comparison is based on the class name. If the names are the same then a comparison is made on the length of the hashable content. Items of the equal-lengthed contents are then successively compared using the same rules. If there is never a difference then 0 is returned.
Examples
>>> from sympy.abc import x, y >>> x.compare(y) -1 >>> x.compare(x) 0 >>> y.compare(x) 1
- doit(**hints)[source]¶
Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via ‘hints’ or unless the ‘deep’ hint was set to ‘False’.
>>> from sympy import Integral >>> from sympy.abc import x
>>> 2*Integral(x, x) 2*Integral(x, x)
>>> (2*Integral(x, x)).doit() x**2
>>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x)
- dummy_eq(other, symbol=None)[source]¶
Compare two expressions and handle dummy symbols.
Examples
>>> from sympy import Dummy >>> from sympy.abc import x, y
>>> u = Dummy('u')
>>> (u**2 + 1).dummy_eq(x**2 + 1) True >>> (u**2 + 1) == (x**2 + 1) False
>>> (u**2 + y).dummy_eq(x**2 + y, x) True >>> (u**2 + y).dummy_eq(x**2 + y, y) False
- property free_symbols: set[Basic]¶
Return from the atoms of self those which are free symbols.
Not all free symbols are
Symbol
(see examples)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 free_symbols method.
Any other method that uses bound variables should implement a free_symbols method.
Examples
>>> from sympy import Derivative, Integral, IndexedBase >>> from sympy.abc import x, y, n >>> (x + 1).free_symbols {x} >>> Integral(x, y).free_symbols {x, y}
Not all free symbols are actually symbols:
>>> IndexedBase('F')[0].free_symbols {F, F[0]}
The symbols of differentiation are not included unless they appear in the expression being differentiated.
>>> Derivative(x + y, y).free_symbols {x, y} >>> Derivative(x, y).free_symbols {x} >>> Derivative(x, (y, n)).free_symbols {n, x}
If you want to know if a symbol is in the variables of the Derivative you can do so as follows:
>>> Derivative(x, y).has_free(y) True
- classmethod fromiter(args, **assumptions)[source]¶
Create a new object from an iterable.
This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first.
Examples
>>> from sympy import Tuple >>> Tuple.fromiter(i for i in range(5)) (0, 1, 2, 3, 4)
- property func¶
The top-level function in an expression.
The following should hold for all objects:
>> x == x.func(*x.args)
Examples
>>> from sympy.abc import x >>> a = 2*x >>> a.func <class 'sympy.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True
- has(*patterns)[source]¶
Test whether any subexpression matches any of the patterns.
Examples
>>> from sympy import sin >>> 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
has
is a structural algorithm with no knowledge of mathematics. Consider the following half-open interval:>>> from sympy import Interval >>> i = Interval.Lopen(0, 5); i Interval.Lopen(0, 5) >>> i.args (0, 5, True, False) >>> i.has(4) # there is no "4" in the arguments False >>> i.has(0) # there *is* a "0" in the arguments True
Instead, use
contains
to determine whether a number is in the interval or not:>>> i.contains(4) True >>> i.contains(0) False
Note that
expr.has(*patterns)
is exactly equivalent toany(expr.has(p) for p in patterns)
. In particular,False
is returned when the list of patterns is empty.>>> x.has() False
- has_free(*patterns)[source]¶
Return True if self has object(s)
x
as a free expression else False.Examples
>>> from sympy import Integral, Function >>> from sympy.abc import x, y >>> f = Function('f') >>> g = Function('g') >>> expr = Integral(f(x), (f(x), 1, g(y))) >>> expr.free_symbols {y} >>> expr.has_free(g(y)) True >>> expr.has_free(*(x, f(x))) False
This works for subexpressions and types, too:
>>> expr.has_free(g) True >>> (x + y + 1).has_free(y + 1) True
- has_xfree(s: set[Basic])[source]¶
Return True if self has any of the patterns in s as a free argument, else False. This is like \(Basic.has_free\) but this will only report exact argument matches.
Examples
>>> from sympy import Function >>> from sympy.abc import x, y >>> f = Function('f') >>> f(x).has_xfree({f}) False >>> f(x).has_xfree({f(x)}) True >>> f(x + 1).has_xfree({x}) True >>> f(x + 1).has_xfree({x + 1}) True >>> f(x + y + 1).has_xfree({x + 1}) False
- property is_comparable¶
Return True if self can be computed to a real number (or already is a real number) with precision, else False.
Examples
>>> from sympy import exp_polar, pi, I >>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False
A False result does not mean that \(self\) cannot be rewritten into a form that would be comparable. For example, the difference computed below is zero but without simplification it does not evaluate to a zero with precision:
>>> e = 2**pi*(1 + 2**pi) >>> dif = e - e.expand() >>> dif.is_comparable False >>> dif.n(2)._prec 1
- is_same(b, approx=None)[source]¶
Return True if a and b are structurally the same, else False. If \(approx\) is supplied, it will be used to test whether two numbers are the same or not. By default, only numbers of the same type will compare equal, so S.Half != Float(0.5).
Examples
In SymPy (unlike Python) two numbers do not compare the same if they are not of the same type:
>>> from sympy import S >>> 2.0 == S(2) False >>> 0.5 == S.Half False
By supplying a function with which to compare two numbers, such differences can be ignored. e.g. \(equal_valued\) will return True for decimal numbers having a denominator that is a power of 2, regardless of precision.
>>> from sympy import Float >>> from sympy.core.numbers import equal_valued >>> (S.Half/4).is_same(Float(0.125, 1), equal_valued) True >>> Float(1, 2).is_same(Float(1, 10), equal_valued) True
But decimals without a power of 2 denominator will compare as not being the same.
>>> Float(0.1, 9).is_same(Float(0.1, 10), equal_valued) False
But arbitrary differences can be ignored by supplying a function to test the equivalence of two numbers:
>>> import math >>> Float(0.1, 9).is_same(Float(0.1, 10), math.isclose) True
Other objects might compare the same even though types are not the same. This routine will only return True if two expressions are identical in terms of class types.
>>> from sympy import eye, Basic >>> eye(1) == S(eye(1)) # mutable vs immutable True >>> Basic.is_same(eye(1), S(eye(1))) False
- match(pattern, old=False)[source]¶
Pattern matching.
Wild symbols match all.
Return
None
when expression (self) does not match with pattern. Otherwise return a dictionary such that:pattern.xreplace(self.match(pattern)) == self
Examples
>>> from sympy import Wild, Sum >>> from sympy.abc import x, y >>> p = Wild("p") >>> q = Wild("q") >>> r = Wild("r") >>> e = (x+y)**(x+y) >>> e.match(p**p) {p_: x + y} >>> e.match(p**q) {p_: x + y, q_: x + y} >>> e = (2*x)**2 >>> e.match(p*q**r) {p_: 4, q_: x, r_: 2} >>> (p*q**r).xreplace(e.match(p*q**r)) 4*x**2
Since match is purely structural expressions that are equivalent up to bound symbols will not match:
>>> print(Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))) None
An expression with bound symbols can be matched if the pattern uses a distinct
Wild
for each bound symbol:>>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p))) {p_: 2, q_: x}
The
old
flag will give the old-style pattern matching where expressions and patterns are essentially solved to give the match. Both of the following give None unlessold=True
:>>> (x - 2).match(p - x, old=True) {p_: 2*x - 2} >>> (2/x).match(p*x, old=True) {p_: 2/x**2}
- matches(expr, repl_dict=None, old=False)[source]¶
Helper method for match() that looks for a match between Wild symbols in self and expressions in expr.
Examples
>>> from sympy import symbols, Wild, Basic >>> a, b, c = symbols('a b c') >>> x = Wild('x') >>> Basic(a + x, x).matches(Basic(a + b, c)) is None True >>> Basic(a + x, x).matches(Basic(a + b + c, b + c)) {x_: b + c}
- rcall(*args)[source]¶
Apply on the argument recursively through the expression tree.
This method is used to simulate a common abuse of notation for operators. For instance, in SymPy the following will not work:
(x+Lambda(y, 2*y))(z) == x+2*z
,however, you can use:
>>> from sympy import Lambda >>> from sympy.abc import x, y, z >>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z
- replace(
- query,
- value,
- map=False,
- simultaneous=True,
- exact=None,
Replace matching subexpressions of
self
withvalue
.If
map = True
then also return the mapping {old: new} whereold
was a sub-expression found with query andnew
is the replacement value for it. If the expression itself does not match the query, then the returned value will beself.xreplace(map)
otherwise it should beself.subs(ordered(map.items()))
.Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The default approach is to do the replacement in a simultaneous fashion so changes made are targeted only once. If this is not desired or causes problems,
simultaneous
can be set to False.In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the
exact
flag is None it will be set to True so the match will only succeed if all non-zero values are received for each Wild that appears in the match pattern. Setting this to False accepts a match of 0; while setting it True accepts all matches that have a 0 in them. See example below for cautions.The list of possible combinations of queries and replacement values is listed below:
Examples
Initial setup
>>> from sympy import log, sin, cos, tan, Wild, Mul, Add >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2))
- 1.1. type -> type
obj.replace(type, newtype)
When object of type
type
is found, replace it with the result of passing its argument(s) tonewtype
.>>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> (x*y).replace(Mul, Add) x + y
- 1.2. type -> func
obj.replace(type, func)
When object of type
type
is found, applyfunc
to its argument(s).func
must be written to handle the number of arguments oftype
.>>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y)
- 2.1. pattern -> expr
obj.replace(pattern(wild), expr(wild))
Replace subexpressions matching
pattern
with the expression written in terms of the Wild symbols inpattern
.>>> a, b = map(Wild, 'ab') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y
Matching is exact by default when more than one Wild symbol is used: matching fails unless the match gives non-zero values for all Wild symbols:
>>> (2*x + y).replace(a*x + b, b - a) y - 2 >>> (2*x).replace(a*x + b, b - a) 2*x
When set to False, the results may be non-intuitive:
>>> (2*x).replace(a*x + b, b - a, exact=False) 2/x
- 2.2. pattern -> func
obj.replace(pattern(wild), lambda wild: expr(wild))
All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression:
>>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2))
- 3.1. func -> func
obj.replace(filter, func)
Replace subexpression
e
withfunc(e)
iffilter(e)
is True.>>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9)
The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice.
>>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1)
When matching a single symbol, \(exact\) will default to True, but this may or may not be the behavior that is desired:
Here, we want \(exact=False\):
>>> from sympy import Function >>> f = Function('f') >>> e = f(1) + f(0) >>> q = f(a), lambda a: f(a + 1) >>> e.replace(*q, exact=False) f(1) + f(2) >>> e.replace(*q, exact=True) f(0) + f(2)
But here, the nature of matching makes selecting the right setting tricky:
>>> e = x**(1 + y) >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(-x - y + 1) >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(1 - y)
It is probably better to use a different form of the query that describes the target expression more precisely:
>>> (1 + x**(1 + y)).replace( ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1, ... lambda x: x.base**(1 - (x.exp - 1))) ... x**(1 - y) + 1
- rewrite(*args, deep=True, **hints)[source]¶
Rewrite self using a defined rule.
Rewriting transforms an expression to another, which is mathematically equivalent but structurally different. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function.
This method takes a pattern and a rule as positional arguments. pattern is optional parameter which defines the types of expressions that will be transformed. If it is not passed, all possible expressions will be rewritten. rule defines how the expression will be rewritten.
- Parameters:
args : Expr
A rule, or pattern and rule. - pattern is a type or an iterable of types. - rule can be any object.
deep : bool, optional
If
True
, subexpressions are recursively transformed. Default isTrue
.
Examples
If pattern is unspecified, all possible expressions are transformed.
>>> from sympy import cos, sin, exp, I >>> from sympy.abc import x >>> expr = cos(x) + I*sin(x) >>> expr.rewrite(exp) exp(I*x)
Pattern can be a type or an iterable of types.
>>> expr.rewrite(sin, exp) exp(I*x)/2 + cos(x) - exp(-I*x)/2 >>> expr.rewrite([cos,], exp) exp(I*x)/2 + I*sin(x) + exp(-I*x)/2 >>> expr.rewrite([cos, sin], exp) exp(I*x)
Rewriting behavior can be implemented by defining
_eval_rewrite()
method.>>> from sympy import Expr, sqrt, pi >>> class MySin(Expr): ... def _eval_rewrite(self, rule, args, **hints): ... x, = args ... if rule == cos: ... return cos(pi/2 - x, evaluate=False) ... if rule == sqrt: ... return sqrt(1 - cos(x)**2) >>> MySin(MySin(x)).rewrite(cos) cos(-cos(-x + pi/2) + pi/2) >>> MySin(x).rewrite(sqrt) sqrt(1 - cos(x)**2)
Defining
_eval_rewrite_as_[...]()
method is supported for backwards compatibility reason. This may be removed in the future and using it is discouraged.>>> class MySin(Expr): ... def _eval_rewrite_as_cos(self, *args, **hints): ... x, = args ... return cos(pi/2 - x, evaluate=False) >>> MySin(x).rewrite(cos) cos(-x + pi/2)
- sort_key(order=None)[source]¶
Return a sort key.
Examples
>>> from sympy import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key()) [1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]") [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
- subs( ) Basic [source]¶
- subs( ) Basic
- subs( ) Basic
Substitutes old for new in an expression after sympifying args.
- \(args\) is either:
two arguments, e.g. foo.subs(old, new)
- one iterable argument, e.g. foo.subs(iterable). The iterable may be
- o an iterable container with (old, new) pairs. In this case the
replacements are processed in the order given with successive patterns possibly affecting replacements already made.
- o a dict or set whose key/value items correspond to old/new pairs.
In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous).
If the keyword
simultaneous
is True, the subexpressions will not be evaluated until all the substitutions have been made.Examples
>>> from sympy import pi, exp, limit, oo >>> from sympy.abc import x, y >>> (1 + x*y).subs(x, pi) pi*y + 1 >>> (1 + x*y).subs({x:pi, y:2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2
>>> (x**2 + x**4).subs(x**2, y) y**2 + y
To replace only the x**2 but not the x**4, use xreplace:
>>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y
To delay evaluation until all substitutions have been made, set the keyword
simultaneous
to True:>>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan
This has the added feature of not allowing subsequent substitutions to affect those already made:
>>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y)
In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted.
>>> from sympy import sqrt, sin, cos >>> from sympy.abc import a, b, c, d, e
>>> A = (sqrt(sin(2*x)), a) >>> B = (sin(2*x), b) >>> C = (cos(2*x), c) >>> D = (x, d) >>> E = (exp(x), e)
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
>>> expr.subs(dict([A, B, C, D, E])) a*c*sin(d*e) + b
The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression:
>>> (x**3 - 3*x).subs({x: oo}) nan
>>> limit(x**3 - 3*x, x, oo) oo
If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as
>>> (1/x).evalf(subs={x: 3.0}, n=21) 0.333333333333333333333
rather than
>>> (1/x).subs({x: 3.0}).evalf(21) 0.333333333333333314830
as the former will ensure that the desired level of precision is obtained.
See also
replace
replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements
xreplace
exact node replacement in expr tree; also capable of using matching rules
sympy.core.evalf.EvalfMixin.evalf
calculates the given formula to a desired level of precision
- xreplace(rule)[source]¶
Replace occurrences of objects within the expression.
- Parameters:
rule : dict-like
Expresses a replacement rule
- Returns:
xreplace : the result of the replacement
Examples
>>> from sympy import symbols, pi, exp >>> x, y, z = symbols('x y z') >>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi
Replacements occur only if an entire node in the expression tree is matched:
>>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) x + exp(y) + 2
xreplace does not differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does:
>>> from sympy import Integral >>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y))
Trying to replace x with an expression raises an error:
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) ValueError: Invalid limits given: ((2*y, 1, 4*y),)
singleton¶
- class sympy.core.singleton.SingletonRegistry[source]¶
The registry for the singleton classes (accessible as
S
).Explanation
This class serves as two separate things.
The first thing it is is the
SingletonRegistry
. Several classes in SymPy appear so often that they are singletonized, that is, using some metaprogramming they are made so that they can only be instantiated once (see thesympy.core.singleton.Singleton
class for details). For instance, every time you createInteger(0)
, this will return the same instance,sympy.core.numbers.Zero
. All singleton instances are attributes of theS
object, soInteger(0)
can also be accessed asS.Zero
.Singletonization offers two advantages: it saves memory, and it allows fast comparison. It saves memory because no matter how many times the singletonized objects appear in expressions in memory, they all point to the same single instance in memory. The fast comparison comes from the fact that you can use
is
to compare exact instances in Python (usually, you need to use==
to compare things).is
compares objects by memory address, and is very fast.Examples
>>> from sympy import S, Integer >>> a = Integer(0) >>> a is S.Zero True
For the most part, the fact that certain objects are singletonized is an implementation detail that users should not need to worry about. In SymPy library code,
is
comparison is often used for performance purposes The primary advantage ofS
for end users is the convenient access to certain instances that are otherwise difficult to type, likeS.Half
(instead ofRational(1, 2)
).When using
is
comparison, make sure the argument is sympified. For instance,>>> x = 0 >>> x is S.Zero False
This problem is not an issue when using
==
, which is recommended for most use-cases:>>> 0 == S.Zero True
The second thing
S
is is a shortcut forsympy.core.sympify.sympify()
.sympy.core.sympify.sympify()
is the function that converts Python objects such asint(1)
into SymPy objects such asInteger(1)
. It also converts the string form of an expression into a SymPy expression, likesympify("x**2")
->Symbol("x")**2
.S(1)
is the same thing assympify(1)
(basically,S.__call__
has been defined to callsympify
).This is for convenience, since
S
is a single letter. It’s mostly useful for defining rational numbers. Consider an expression likex + 1/2
. If you enter this directly in Python, it will evaluate the1/2
and give0.5
, because both arguments are ints (see also Two Final Notes: ^ and /). However, in SymPy, you usually want the quotient of two integers to give an exact rational number. The way Python’s evaluation works, at least one side of an operator needs to be a SymPy object for the SymPy evaluation to take over. You could write this asx + Rational(1, 2)
, but this is a lot more typing. A shorter version isx + S(1)/2
. SinceS(1)
returnsInteger(1)
, the division will return aRational
type, since it will callInteger.__truediv__
, which knows how to return aRational
.
- class sympy.core.singleton.Singleton(*args, **kwargs)[source]¶
Metaclass for singleton classes.
Explanation
A singleton class has only one instance which is returned every time the class is instantiated. Additionally, this instance can be accessed through the global registry object
S
asS.<class_name>
.Examples
>>> from sympy import S, Basic >>> from sympy.core.singleton import Singleton >>> class MySingleton(Basic, metaclass=Singleton): ... pass >>> Basic() is Basic() False >>> MySingleton() is MySingleton() True >>> S.MySingleton is MySingleton() True
Notes
Instance creation is delayed until the first time the value is accessed. (SymPy versions before 1.0 would create the instance during class creation time, which would be prone to import cycles.)
expr¶
- class sympy.core.expr.Expr(*args)[source]¶
Base class for algebraic expressions.
Explanation
Everything that requires arithmetic operations to be defined should subclass this class, instead of Basic (which should be used only for argument storage and expression manipulation, i.e. pattern matching, substitutions, etc).
If you want to override the comparisons of expressions: Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch. _eval_is_ge return true if x >= y, false if x < y, and None if the two types are not comparable or the comparison is indeterminate
See also
- args_cnc(cset=False, warn=True, split_1=True)[source]¶
Return [commutative factors, non-commutative factors] of self.
Explanation
self is treated as a Mul and the ordering of the factors is maintained. If
cset
is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly suppressed by settingwarn
to False.Note: -1 is always separated from a Number unless split_1 is False.
Examples
>>> from sympy import symbols, oo >>> A, B = symbols('A B', commutative=0) >>> x, y = symbols('x y') >>> (-2*x*y).args_cnc() [[-1, 2, x, y], []] >>> (-2.5*x).args_cnc() [[-1, 2.5, x], []] >>> (-2*x*A*B*y).args_cnc() [[-1, 2, x, y], [A, B]] >>> (-2*x*A*B*y).args_cnc(split_1=False) [[-2, x, y], [A, B]] >>> (-2*x*y).args_cnc(cset=True) [{-1, 2, x, y}, []]
The arg is always treated as a Mul:
>>> (-2 + x + A).args_cnc() [[], [x - 2 + A]] >>> (-oo).args_cnc() # -oo is a singleton [[-1, oo], []]
- as_coeff_Add(
- rational=False,
Efficiently extract the coefficient of a summation.
- as_coeff_Mul(
- rational: bool = False,
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 do not 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 do not 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).as_coeff_add() (3, (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_mul(
- *deps,
- **kwargs,
Return the tuple (c, args) where self is written as a Mul,
m
.c should be a Rational multiplied by any factors of the Mul that are independent of deps.
args should be a tuple of all other factors 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 do not 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 do not 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_coefficient(
- expr: Expr,
Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into the product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.
Examples
>>> from sympy import E, pi, sin, I, Poly >>> from sympy.abc import x
>>> E.as_coefficient(E) 1 >>> (2*E).as_coefficient(E) 2 >>> (2*sin(E)*E).as_coefficient(E)
Two terms have E in them so a sum is returned. (If one were desiring the coefficient of the term exactly matching E then the constant from the returned expression could be selected. Or, for greater precision, a method of Poly can be used to indicate the desired term from which the coefficient is desired.)
>>> (2*E + x*E).as_coefficient(E) x + 2 >>> _.args[0] # just want the exact match 2 >>> p = Poly(2*E + x*E); p Poly(x*E + 2*E, x, E, domain='ZZ') >>> p.coeff_monomial(E) 2 >>> p.nth(0, 1) 2
Since the following cannot be written as a product containing E as a factor, None is returned. (If the coefficient
2*x
is desired then thecoeff
method should be used.)>>> (2*E*x + x).as_coefficient(E) >>> (2*E*x + x).coeff(E) 2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I) 2 >>> (2*I).as_coefficient(pi*I)
See also
coeff
return sum of terms have a given factor
as_coeff_Add
separate the additive constant from an expression
as_coeff_Mul
separate the multiplicative constant from an expression
as_independent
separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial
efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth
like coeff_monomial but powers of monomial terms are used
- as_coefficients_dict(*syms)[source]¶
Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0.
If symbols
syms
are provided, any multiplicative terms independent of them will be considered a coefficient and a regular dictionary of syms-dependent generators as keys and their corresponding coefficients as values will be returned.Examples
>>> from sympy.abc import a, x, y >>> (3*x + a*x + 4).as_coefficients_dict() {1: 4, x: 3, a*x: 1} >>> _[a] 0 >>> (3*a*x).as_coefficients_dict() {a*x: 3} >>> (3*a*x).as_coefficients_dict(x) {x: 3*a} >>> (3*a*x).as_coefficients_dict(y) {1: 3*a*x}
- as_content_primitive(
- radical=False,
- clear=True,
This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and
Mul(*foo.as_content_primitive()) == foo
. The primitive need not be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self).Examples
>>> from sympy import sqrt >>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)
The as_content_primitive function is recursive and retains structure:
>>> eq.as_content_primitive() (2, x + 3*y*(y + 1) + 1)
Integer powers will have Rationals extracted from the base:
>>> ((2 + 6*x)**2).as_content_primitive() (4, (3*x + 1)**2) >>> ((2 + 6*x)**(2*y)).as_content_primitive() (1, (2*(3*x + 1))**(2*y))
Terms may end up joining once their as_content_primitives are added:
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (11, x*(y + 1)) >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (9, x*(y + 1)) >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive() (1, 6.0*x*(y + 1) + 3*z*(y + 1)) >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() (121, x**2*(y + 1)**2) >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive() (1, 4.84*x**2*(y + 1)**2)
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))
If clear=False (default is True) then content will not be removed from an Add if it can be distributed to leave one or more terms with integer coefficients.
>>> (x/2 + y).as_content_primitive() (1/2, x + 2*y) >>> (x/2 + y).as_content_primitive(clear=False) (1, x/2 + y)
- as_expr(*gens)[source]¶
Convert a polynomial to a SymPy expression.
Examples
>>> from sympy import sin >>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y) >>> f.as_expr() x**2 + x*y
>>> sin(x).as_expr() sin(x)
- as_independent(
- *deps,
- **hint,
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 and to always return (0, 0) for \(self\) of zero regardless of hints.
For nonzero \(self\), the returned tuple (i, d) has the following interpretation:
i will has no variable that appears in deps
d will either have terms that contain variables that are in deps, or be equal to 0 (when self is an Add) or 1 (when self is a Mul)
if self is an Add then self = i + d
if self is a Mul then self = i*d
otherwise (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=True) (0, 3*x)
– force self to be treated as a Mul:
>>> (3+x).as_independent(x, as_Add=False) (1, x + 3) >>> (-3+x).as_independent(x, as_Add=False) (1, x - 3)
Note how the below differs from the above in making the constant on the dep term positive.
>>> (y*(-3+x)).as_independent(x) (y, x - 3)
- – use .as_independent() for true independence testing instead
of .has(). The former considers only symbols in the free symbols while the latter considers all symbols
>>> from sympy import Integral >>> I = Integral(x, (x, 1, 2)) >>> I.has(x) True >>> x in I.free_symbols False >>> I.as_independent(x) == (I, 1) True >>> (I + x).as_independent(x) == (I, x) True
Note: when trying to get independent terms, a separation method might need to be used first. In this case, it is important to keep track of what you send to this routine so you know how to interpret the returned values
>>> from sympy import separatevars, log >>> separatevars(exp(x+y)).as_independent(x) (exp(y), exp(x)) >>> (x + x*y).as_independent(y) (x, x*y) >>> separatevars(x + x*y).as_independent(y) (x, y + 1) >>> (x*(1 + y)).as_independent(y) (x, y + 1) >>> (x*(1 + y)).expand(mul=True).as_independent(y) (x, x*y) >>> a, b=symbols('a b', positive=True) >>> (log(a*b).expand(log=True)).as_independent(b) (log(a), log(b))
- as_leading_term(*symbols, logx=None, cdir=0)[source]¶
Returns the leading (nonzero) term of the series expansion of self.
The _eval_as_leading_term routines are used to do this, and they must always return a non-zero value.
Examples
>>> from sympy.abc import x >>> (1 + x + x**2).as_leading_term(x) 1 >>> (1/x**2 + x + x**2).as_leading_term(x) x**(-2)
- as_numer_denom() tuple[Expr, Expr] [source]¶
Return the numerator and the denominator of an expression.
expression -> a/b -> a, b
This is just a stub that should be defined by an object’s class methods to get anything else.
See also
normal
return
a/b
instead of(a, b)
- as_ordered_terms(order=None, data=False)[source]¶
Transform an expression to an ordered list of terms.
Examples
>>> from sympy import sin, cos >>> from sympy.abc import x
>>> (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)[source]¶
Converts
self
to a polynomial or returnsNone
.Explanation
>>> from sympy import sin >>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y)) None
- as_powers_dict()[source]¶
Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary.
See also
as_ordered_factors
An alternative for noncommutative applications, returning an ordered list of factors.
args_cnc
Similar to as_ordered_factors, but guarantees separation of commutative and noncommutative factors.
- as_real_imag(
- deep=True,
- **hints,
Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method cannot be confused with re() and im() functions, which does not perform complex expansion at evaluation.
However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.
>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag() (x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag() (re(z) - im(w), re(w) + im(z))
- aseries(x=None, n=6, bound=0, hir=False)[source]¶
Asymptotic Series expansion of self. This is equivalent to
self.series(x, oo, n)
.- Parameters:
self : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
n : Value
The value used to represent the order in terms of
x**n
, up to which the series is to be expanded.hir : Boolean
Set this parameter to be True to produce hierarchical series. It stops the recursion at an early level and may provide nicer and more useful results.
bound : Value, Integer
Use the
bound
parameter to give limit on rewriting coefficients in its normalised form.- Returns:
Expr
Asymptotic series expansion of the expression.
Examples
>>> from sympy import sin, exp >>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x) (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True) -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x) exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3) exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))
For rational expressions this method may return original expression without the Order term. >>> (1/x).aseries(x, n=8) 1/x
Notes
This algorithm is directly induced from the limit computational algorithm provided by Gruntz. It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first to look for the most rapidly varying subexpression w of a given expression f and then expands f in a series in w. Then same thing is recursively done on the leading coefficient till we get constant coefficients.
If the most rapidly varying subexpression of a given expression f is f itself, the algorithm tries to find a normalised representation of the mrv set and rewrites f using this normalised representation.
If the expansion contains an order term, it will be either
O(x ** (-n))
orO(w ** (-n))
wherew
belongs to the most rapidly varying expression ofself
.See also
Expr.aseries
See the docstring of this function for complete details of this wrapper.
References
- coeff(
- x: Expr,
- n=1,
- right=False,
- _first=True,
Returns the coefficient from the term(s) containing
x**n
. Ifn
is zero then all terms independent ofx
will be returned.Explanation
When
x
is noncommutative, the coefficient to the left (default) or right ofx
can be returned. The keyword ‘right’ is ignored whenx
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) 0
You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None):
>>> (3 + 2*x + 4*x**2).coeff(x, 0) 3 >>> eq = ((x + 1)**3).expand() + 1 >>> eq x**3 + 3*x**2 + 3*x + 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 2] >>> eq -= 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 0]
You can select terms that have a numerical term in front of them:
>>> (-x - 2*y).coeff(2) -y >>> from sympy import sqrt >>> (x + sqrt(2)*x).coeff(sqrt(2)) x
The matching is exact:
>>> (3 + 2*x + 4*x**2).coeff(x) 2 >>> (3 + 2*x + 4*x**2).coeff(x**2) 4 >>> (3 + 2*x + 4*x**2).coeff(x**3) 0 >>> (z*(x + y)**2).coeff((x + y)**2) z >>> (z*(x + y)**2).coeff(x + y) 0
In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following:
>>> (x + z*(x + x*y)).coeff(x) 1
If such factoring is desired, factor_terms can be used first:
>>> from sympy import factor_terms >>> factor_terms(x + z*(x + x*y)).coeff(x) z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False) >>> n.coeff(n) 1 >>> (3*n).coeff(n) 3 >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m 1 + m >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m m
If there is more than one possible coefficient 0 is returned:
>>> (n*m + m*n).coeff(n) 0
If there is only one possible coefficient, it is returned:
>>> (n*m + x*m*n).coeff(m*n) x >>> (n*m + x*m*n).coeff(m*n, right=1) 1
See also
as_coefficient
separate the expression into a coefficient and factor
as_coeff_Add
separate the additive constant from an expression
as_coeff_Mul
separate the multiplicative constant from an expression
as_independent
separate x-dependent terms/factors from others
sympy.polys.polytools.Poly.coeff_monomial
efficiently find the single coefficient of a monomial in Poly
sympy.polys.polytools.Poly.nth
like coeff_monomial but powers of monomial terms are used
- collect(
- syms,
- func=None,
- evaluate=True,
- exact=False,
- distribute_order_term=True,
See the collect function in sympy.simplify
- compute_leading_term(x, logx=None)[source]¶
Deprecated function to compute the leading term of a series.
as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first.
- could_extract_minus_sign() bool [source]¶
Return True if self has -1 as a leading factor or has more literal negative signs than positive signs in a sum, otherwise False.
Examples
>>> from sympy.abc import x, y >>> e = x - y >>> {i.could_extract_minus_sign() for i in (e, -e)} {False, True}
Though the
y - x
is considered like-(x - y)
, since it is in a product without a leading factor of -1, the result is false below:>>> (x*(y - x)).could_extract_minus_sign() False
To put something in canonical form wrt to sign, use \(signsimp\):
>>> from sympy import signsimp >>> signsimp(x*(y - x)) -x*(x - y) >>> _.could_extract_minus_sign() True
- equals(other, failing_expression=False)[source]¶
Return True if self == other, False if it does not, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.
Explanation
If
self
is a Number (or complex number) that is not zero, then the result is False.If
self
is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either -1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False.
- expand(
- 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 of the expand() function in sympy.core.function for more information.
- property expr_free_symbols¶
Like
free_symbols
, but returns the free symbols only if they are contained in an expression node.Examples
>>> from sympy.abc import x, y >>> (x + y).expr_free_symbols {x, y}
If the expression is contained in a non-expression object, do not return the free symbols. Compare:
>>> from sympy import Tuple >>> t = Tuple(x + y) >>> t.expr_free_symbols set() >>> t.free_symbols {x, y}
- extract_additively(c)[source]¶
Return self - c if it’s possible to subtract c from self and make all matching coefficients move towards zero, else return None.
Examples
>>> from sympy.abc import x, y >>> e = 2*x + 3 >>> e.extract_additively(x + 1) x + 2 >>> e.extract_additively(3*x) >>> e.extract_additively(4) >>> (y*(x + 1)).extract_additively(x + 1) >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1) (x + 1)*(x + 2*y) + 3
See also
- extract_branch_factor(allow_half=False)[source]¶
Try to write self as
exp_polar(2*pi*I*n)*z
in a nice way. Return (z, n).>>> from sympy import exp_polar, I, pi >>> from sympy.abc import x, y >>> exp_polar(I*pi).extract_branch_factor() (exp_polar(I*pi), 0) >>> exp_polar(2*I*pi).extract_branch_factor() (1, 1) >>> exp_polar(-pi*I).extract_branch_factor() (exp_polar(I*pi), -1) >>> exp_polar(3*pi*I + x).extract_branch_factor() (exp_polar(x + I*pi), 1) >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor() (y*exp_polar(2*pi*x), -1) >>> exp_polar(-I*pi/2).extract_branch_factor() (exp_polar(-I*pi/2), 0)
If allow_half is True, also extract exp_polar(I*pi):
>>> exp_polar(I*pi).extract_branch_factor(allow_half=True) (1, 1/2) >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True) (1, 1) >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True) (1, 3/2) >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True) (1, -1/2)
- extract_multiplicatively(
- c: Expr,
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.
Examples
>>> 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
- fourier_series(limits=None)[source]¶
Compute fourier sine/cosine series of self.
See the docstring of the
fourier_series()
in sympy.series.fourier for more information.
- fps(
- x=None,
- x0=0,
- dir=1,
- hyper=True,
- order=4,
- rational=True,
- full=False,
Compute formal power power series of self.
See the docstring of the
fps()
function in sympy.series.formal for more information.
- getn()[source]¶
Returns the order of the expression.
Explanation
The order is determined either from the O(…) term. If there is no O(…) term, it returns None.
Examples
>>> from sympy import O >>> from sympy.abc import x >>> (1 + x + O(x**2)).getn() 2 >>> (1 + x).getn()
- invert(g, *gens, **args)[source]¶
Return the multiplicative inverse of
self
modg
whereself
(andg
) may be symbolic expressions).
- is_algebraic_expr(*syms)[source]¶
This tests whether a given expression is algebraic or not, 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 “algebraic expressions” with symbolic exponents. This is a simple extension to the is_rational_function, including rational exponentiation.
Examples
>>> from sympy import Symbol, sqrt >>> x = Symbol('x', real=True) >>> sqrt(1 + x).is_rational_function() False >>> sqrt(1 + x).is_algebraic_expr() True
This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be an algebraic expression to become one.
>>> from sympy import exp, factor >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1) >>> a.is_algebraic_expr(x) False >>> factor(a).is_algebraic_expr() True
See also
References
- is_constant(*wrt, **flags)[source]¶
Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.
Explanation
If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, a few strategies are tried:
1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if
wrt
is different than the free symbols.2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.
3) finding out zeros of denominator expression with free_symbols. It will not be constant if there are zeros. It gives more negative answers for expression that are not constant.
If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag
failing_number
is True – in that case the numerical value will be returned.If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.
Examples
>>> from sympy import cos, sin, Sum, S, pi >>> from sympy.abc import a, n, x, y >>> x.is_constant() False >>> S(2).is_constant() True >>> Sum(x, (x, 1, 10)).is_constant() True >>> Sum(x, (x, 1, n)).is_constant() False >>> Sum(x, (x, 1, n)).is_constant(y) True >>> Sum(x, (x, 1, n)).is_constant(n) False >>> Sum(x, (x, 1, n)).is_constant(x) True >>> eq = a*cos(x)**2 + a*sin(x)**2 - a >>> eq.is_constant() True >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 True
>>> (0**x).is_constant() False >>> x.is_constant() False >>> (x**x).is_constant() False >>> one = cos(x)**2 + sin(x)**2 >>> one.is_constant() True >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1 True
- is_meromorphic(x, a)[source]¶
This tests whether an expression is meromorphic as a function of the given symbol
x
at the pointa
.This method is intended as a quick test that will return None if no decision can be made without simplification or more detailed analysis.
Examples
>>> from sympy import zoo, log, sin, sqrt >>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3 >>> f.is_meromorphic(x, 0) True >>> f.is_meromorphic(x, 1) True >>> f.is_meromorphic(x, zoo) True
>>> g = x**log(3) >>> g.is_meromorphic(x, 0) False >>> g.is_meromorphic(x, 1) True >>> g.is_meromorphic(x, zoo) False
>>> h = sin(1/x)*x**2 >>> h.is_meromorphic(x, 0) False >>> h.is_meromorphic(x, 1) True >>> h.is_meromorphic(x, zoo) True
Multivalued functions are considered meromorphic when their branches are meromorphic. Thus most functions are meromorphic everywhere except at essential singularities and branch points. In particular, they will be meromorphic also on branch cuts except at their endpoints.
>>> log(x).is_meromorphic(x, -1) True >>> log(x).is_meromorphic(x, 0) False >>> sqrt(x).is_meromorphic(x, -1) True >>> sqrt(x).is_meromorphic(x, 0) False
- property is_number¶
Returns True if
self
has no free symbols and no undefined functions (AppliedUndef, to be precise). It will be faster thanif not self.free_symbols
, however, sinceis_number
will fail as soon as it hits a free symbol or undefined function.Examples
>>> from sympy import Function, Integral, cos, sin, pi >>> from sympy.abc import x >>> f = Function('f')
>>> x.is_number False >>> f(1).is_number False >>> (2*x).is_number False >>> (2 + Integral(2, x)).is_number False >>> (2 + Integral(2, (x, 1, 2))).is_number True
Not all numbers are Numbers in the SymPy sense:
>>> pi.is_number, pi.is_Number (True, False)
If something is a number it should evaluate to a number with real and imaginary parts that are Numbers; the result may not be comparable, however, since the real and/or imaginary part of the result may not have precision.
>>> cos(1).is_number and cos(1).is_comparable True
>>> z = cos(1)**2 + sin(1)**2 - 1 >>> z.is_number True >>> z.is_comparable False
See also
- is_polynomial(*syms)[source]¶
Return True if self is a polynomial in syms and False otherwise.
This checks if self is an exact polynomial in syms. This function returns False for expressions that are “polynomials” with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, *syms) should work 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, Function >>> 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 >>> (2**x + 1).is_polynomial(2**x) True >>> f = Function('f') >>> (f(x) + 1).is_polynomial(x) False >>> (f(x) + 1).is_polynomial(f(x)) True >>> (1/f(x) + 1).is_polynomial(f(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_rational_function(*syms)[source]¶
Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.
This function returns False for expressions that are “rational functions” with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True.
This is not part of the assumptions system. You cannot do Symbol(‘z’, rational_function=True).
Examples
>>> from sympy import Symbol, sin >>> from sympy.abc import x, y
>>> (x/y).is_rational_function() True
>>> (x**2).is_rational_function() True
>>> (x/sin(y)).is_rational_function(y) False
>>> n = Symbol('n', integer=True) >>> (x**n + 1).is_rational_function(x) False
This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one.
>>> from sympy import sqrt, factor >>> 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_algebraic_expr().
- leadterm(x, logx=None, cdir=0)[source]¶
Returns the leading term a*x**b as a tuple (a, b).
Examples
>>> from sympy.abc import x >>> (1+x+x**2).leadterm(x) (1, 0) >>> (1/x**2+x+x**2).leadterm(x) (1, -2)
- lseries(
- x=None,
- x0=0,
- dir='+',
- logx=None,
- cdir=0,
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 do not know how many you should ask for in nseries() using the “n” parameter.
See also nseries().
- normal()[source]¶
Return the expression as a fraction.
expression -> a/b
See also
as_numer_denom
return
(a, b)
instead ofa/b
- nseries(
- x=None,
- x0=0,
- n=6,
- dir='+',
- logx=None,
- cdir=0,
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.
The optional
logx
parameter can be used to replace any log(x) in the returned series with a symbolic value to avoid evaluating log(x) at 0. A symbol to use in place of log(x) should be provided.Advantage – it’s fast, because we do not 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().
Examples
>>> from sympy import sin, log, Symbol >>> from sympy.abc import x, y >>> sin(x).nseries(x, 0, 6) x - x**3/6 + x**5/120 + O(x**6) >>> log(x+1).nseries(x, 0, 5) x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
Handling of the
logx
parameter — in the following example the expansion fails sincesin
does not have an asymptotic expansion at -oo (the limit of log(x) as x approaches 0):>>> e = sin(log(x)) >>> e.nseries(x, 0, 6) Traceback (most recent call last): ... PoleError: ... ... >>> logx = Symbol('logx') >>> e.nseries(x, 0, 6, logx=logx) sin(logx)
In the following example, the expansion works but only returns self unless the
logx
parameter is used:>>> e = x**y >>> e.nseries(x, 0, 2) x**y >>> e.nseries(x, 0, 2, logx=logx) exp(logx*y)
- nsimplify(
- constants=(),
- tolerance=None,
- full=False,
See the nsimplify function in sympy.simplify
- primitive() tuple[Number, Expr] [source]¶
Return the positive Rational that can be extracted non-recursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float).
Examples
>>> from sympy.abc import x >>> (3*(x + 1)**2).primitive() (3, (x + 1)**2) >>> a = (6*x + 2); a.primitive() (2, 3*x + 1) >>> b = (x/2 + 3); b.primitive() (1/2, x + 6) >>> (a*b).primitive() == (1, a*b) True
- round(n=None)[source]¶
Return x rounded to the given decimal place.
If a complex number would results, apply round to the real and imaginary components of the number.
Examples
>>> from sympy import pi, E, I, S, Number >>> pi.round() 3 >>> pi.round(2) 3.14 >>> (2*pi + E*I).round() 6 + 3*I
The round method has a chopping effect:
>>> (2*pi + I/10).round() 6 >>> (pi/10 + 2*I).round() 2*I >>> (pi/10 + E*I).round(2) 0.31 + 2.72*I
Notes
The Python
round
function uses the SymPyround
method so it will always return a SymPy number (not a Python float or int):>>> isinstance(round(S(123), -2), Number) True
- series(
- x=None,
- x0=0,
- n=6,
- dir='+',
- logx=None,
- cdir=0,
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.Returns the series expansion of “self” around the point
x = x0
with respect tox
up toO((x - x0)**n, x, x0)
(default n is 6).If
x=None
andself
is univariate, the univariate symbol will be supplied, otherwise an error will be raised.- Parameters:
expr : Expression
The expression whose series is to be expanded.
x : Symbol
It is the variable of the expression to be calculated.
x0 : Value
The value around which
x
is calculated. Can be any value from-oo
tooo
.n : Value
The value used to represent the order in terms of
x**n
, up to which the series is to be expanded.dir : String, optional
The series-expansion can be bi-directional. If
dir="+"
, then (x->x0+). Ifdir="-", then (x->x0-). For infinite ``x0
(oo
or-oo
), thedir
argument is determined from the direction of the infinity (i.e.,dir="-"
foroo
).logx : optional
It is used to replace any log(x) in the returned series with a symbolic value rather than evaluating the actual value.
cdir : optional
It stands for complex direction, and indicates the direction from which the expansion needs to be evaluated.
- Returns:
Expr : Expression
Series expansion of the expression about x0
- Raises:
TypeError
If “n” and “x0” are infinity objects
PoleError
If “x0” is an infinity object
Examples
>>> from sympy import cos, exp, tan >>> 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) >>> cos(x).series(x, x0=1, n=2) cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1)) >>> 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 a generator of the series terms will be returned.>>> term=cos(x).series(n=None) >>> [next(term) for i in range(2)] [1, -x**2/2]
For
dir=+
(default) the series is calculated from the right and fordir=-
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 >>> f = tan(x) >>> f.series(x, 2, 6, "+") tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) + (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 + 5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 + 2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-") tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2)) + O((x - 2)**3, (x, 2))
For rational expressions this method may return original expression without the Order term. >>> (1/x).series(x, n=8) 1/x
symbol¶
- class sympy.core.symbol.Symbol(name, **assumptions)[source]¶
Symbol class is used to create symbolic variables.
- Parameters:
AtomicExpr: variable name
Boolean: Assumption with a boolean value(True or False)
Explanation
Symbolic variables are placeholders for mathematical symbols that can represent numbers, constants, or any other mathematical entities and can be used in mathematical expressions and to perform symbolic computations.
Assumptions:
commutative = True positive = True real = True imaginary = True complex = True complete list of more assumptions- Predicates
You can override the default assumptions in the constructor.
Examples
>>> from sympy import Symbol >>> x = Symbol("x", positive=True) >>> x.is_positive True >>> x.is_negative False
passing in greek letters:
>>> from sympy import Symbol >>> alpha = Symbol('alpha') >>> alpha α
Trailing digits are automatically treated like subscripts of what precedes them in the name. General format to add subscript to a symbol :
<var_name> = Symbol('<symbol_name>_<subscript>')
>>> from sympy import Symbol >>> alpha_i = Symbol('alpha_i') >>> alpha_i αᵢ
- class sympy.core.symbol.Wild(
- name,
- exclude=(),
- properties=(),
- **assumptions,
A Wild symbol matches anything, or anything without whatever is explicitly excluded.
- Parameters:
name : str
Name of the Wild instance.
exclude : iterable, optional
Instances in
exclude
will not be matched.properties : iterable of functions, optional
Functions, each taking an expressions as input and returns a
bool
. All functions inproperties
need to returnTrue
in order for the Wild instance to match the expression.
Examples
>>> from sympy import Wild, WildFunction, cos, pi >>> from sympy.abc import x, y, z >>> a = Wild('a') >>> x.match(a) {a_: x} >>> pi.match(a) {a_: pi} >>> (3*x**2).match(a*x) {a_: 3*x} >>> cos(x).match(a) {a_: cos(x)} >>> b = Wild('b', exclude=[x]) >>> (3*x**2).match(b*x) >>> b.match(a) {a_: b_} >>> A = WildFunction('A') >>> A.match(a) {a_: A_}
Tips
When using Wild, be sure to use the exclude keyword to make the pattern more precise. Without the exclude pattern, you may get matches that are technically correct, but not what you wanted. For example, using the above without exclude:
>>> from sympy import symbols >>> a, b = symbols('a b', cls=Wild) >>> (2 + 3*y).match(a*x + b*y) {a_: 2/x, b_: 3}
This is technically correct, because (2/x)*x + 3*y == 2 + 3*y, but you probably wanted it to not match at all. The issue is that you really did not want a and b to include x and y, and the exclude parameter lets you specify exactly this. With the exclude parameter, the pattern will not match.
>>> a = Wild('a', exclude=[x, y]) >>> b = Wild('b', exclude=[x, y]) >>> (2 + 3*y).match(a*x + b*y)
Exclude also helps remove ambiguity from matches.
>>> E = 2*x**3*y*z >>> a, b = symbols('a b', cls=Wild) >>> E.match(a*b) {a_: 2*y*z, b_: x**3} >>> a = Wild('a', exclude=[x, y]) >>> E.match(a*b) {a_: z, b_: 2*x**3*y} >>> a = Wild('a', exclude=[x, y, z]) >>> E.match(a*b) {a_: 2, b_: x**3*y*z}
Wild also accepts a
properties
parameter:>>> a = Wild('a', properties=[lambda k: k.is_Integer]) >>> E.match(a*b) {a_: 2, b_: x**3*y*z}
- class sympy.core.symbol.Dummy(name=None, dummy_index=None, **assumptions)[source]¶
Dummy symbols are each unique, even if they have the same name:
Examples
>>> from sympy import Dummy >>> Dummy("x") == Dummy("x") False
If a name is not supplied then a string value of an internal count 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() _Dummy_10
- sympy.core.symbol.symbols(
- names,
- *,
- cls=<class 'sympy.core.symbol.Symbol'>,
- **args,
Transform strings into instances of
Symbol
class.symbols()
function returns a sequence of symbols with names taken fromnames
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({'a', 'b', 'c'}) {a, b, c}
If an iterable container is needed for a single symbol, set the
seq
argument toTrue
or terminate the symbol name with a comma:>>> symbols('x', seq=True) (x,)
To reduce typing, range syntax is supported to create indexed symbols. Ranges are indicated by a colon and the type of range is determined by the character to the right of the colon. If the character is a digit then all contiguous digits to the left are taken as the nonnegative starting value (or 0 if there is no digit left of the colon) and all contiguous digits to the right are taken as 1 greater than the ending value:
>>> symbols('x:10') (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) >>> symbols('x5:10') (x5, x6, x7, x8, x9) >>> symbols('x5(:2)') (x50, x51) >>> 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))
If the character to the right of the colon is a letter, then the single letter to the left (or ‘a’ if there is none) is taken as the start and all characters in the lexicographic range through the letter to the right are used as the range:
>>> symbols('x:z') (x, y, z) >>> symbols('x:c') # null range () >>> symbols('x(:c)') (xa, xb, xc) >>> symbols(':c') (a, b, c) >>> symbols('a:d, x:z') (a, b, c, d, x, y, z) >>> symbols(('a:d', 'x:z')) ((a, b, c, d), (x, y, z))
Multiple ranges are supported; contiguous numerical ranges should be separated by parentheses to disambiguate the ending number of one range from the starting number of the next:
>>> symbols('x:2(1:3)') (x01, x02, x11, x12) >>> symbols(':3:2') # parsing is from left to right (00, 01, 10, 11, 20, 21)
Only one pair of parentheses surrounding ranges are removed, so to include parentheses around ranges, double them. And to include spaces, commas, or colons, escape them with a backslash:
>>> symbols('x((a:b))') (x(a), x(b)) >>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))' (x(0,0), x(0,1))
All newly created symbols have assumptions set according 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 like instances of Function or Wild classes. To achieve this, setcls
keyword argument to the desired type:>>> symbols('f,g,h', cls=Function) (f, g, h) >>> type(_[0]) <class 'sympy.core.function.UndefinedFunction'>
- sympy.core.symbol.var(names, **args)[source]¶
Create symbols and inject them into the global namespace.
Explanation
This calls
symbols()
with the same arguments and puts the results into the global namespace. It’s recommended not to usevar()
in library code, wheresymbols()
has to be used:.. rubric:: Examples
>>> from sympy import var
>>> var('x') x >>> x # noqa: F821 x
>>> var('a,ab,abc') (a, ab, abc) >>> abc # noqa: F821 abc
>>> var('x,y', real=True) (x, y) >>> x.is_real and y.is_real # noqa: F821 True
See
symbols()
documentation for more details on what kinds of arguments can be passed tovar()
.
intfunc¶
- sympy.core.intfunc.num_digits(n, base=10)[source]¶
Return the number of digits needed to express n in give base.
- Parameters:
n: integer
The number whose digits are counted.
b: integer
The base in which digits are computed.
Examples
>>> from sympy.core.intfunc import num_digits >>> num_digits(10) 2 >>> num_digits(10, 2) # 1010 -> 4 digits 4 >>> num_digits(-100, 16) # -64 -> 2 digits 2
- sympy.core.intfunc.trailing(n)[source]¶
Count the number of trailing zero digits in the binary representation of n, i.e. determine the largest power of 2 that divides n.
Examples
>>> from sympy import trailing >>> trailing(128) 7 >>> trailing(63) 0
See also
- sympy.core.intfunc.ilcm(*args)[source]¶
Computes integer least common multiple.
Examples
>>> from sympy import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30
- sympy.core.intfunc.igcd(*args)¶
Computes nonnegative integer greatest common divisor.
Explanation
The algorithm is based on the well known Euclid’s algorithm [R123]. To improve speed,
igcd()
has its own caching mechanism. If you do not need the cache mechanism, usingsympy.external.gmpy.gcd
.Examples
>>> from sympy import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5
References
- sympy.core.intfunc.igcd_lehmer(a, b)[source]¶
Computes greatest common divisor of two integers.
Explanation
Euclid’s algorithm for the computation of the greatest common divisor
gcd(a, b)
of two (positive) integers \(a\) and \(b\) is based on the division identity $$ a = q \times b + r$$, where the quotient \(q\) and the remainder \(r\) are integers and \(0 \le r < b\). Then each common divisor of \(a\) and \(b\) divides \(r\), and it follows thatgcd(a, b) == gcd(b, r)
. The algorithm works by constructing the sequence r0, r1, r2, …, where r0 = a, r1 = b, and each rn is the remainder from the division of the two preceding elements.In Python,
q = a // b
andr = a % b
are obtained by the floor division and the remainder operations, respectively. These are the most expensive arithmetic operations, especially for large a and b.Lehmer’s algorithm [R124] is based on the observation that the quotients
qn = r(n-1) // rn
are in general small integers even when a and b are very large. Hence the quotients can be usually determined from a relatively small number of most significant bits.The efficiency of the algorithm is further enhanced by not computing each long remainder in Euclid’s sequence. The remainders are linear combinations of a and b with integer coefficients derived from the quotients. The coefficients can be computed as far as the quotients can be determined from the chosen most significant parts of a and b. Only then a new pair of consecutive remainders is computed and the algorithm starts anew with this pair.
References
- sympy.core.intfunc.igcdex(a, b)[source]¶
Returns x, y, g such that g = x*a + y*b = gcd(a, b).
Examples
>>> from sympy.core.intfunc import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2)
>>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4
- sympy.core.intfunc.isqrt(n)[source]¶
Return the largest integer less than or equal to \(\sqrt{n}\).
- Parameters:
n : non-negative integer
- Returns:
int : \(\left\lfloor\sqrt{n}\right\rfloor\)
- Raises:
ValueError
If n is negative.
TypeError
If n is of a type that cannot be compared to
int
. Therefore, a TypeError is raised forstr
, but not forfloat
.
Examples
>>> from sympy.core.intfunc import isqrt >>> isqrt(0) 0 >>> isqrt(9) 3 >>> isqrt(10) 3 >>> isqrt("30") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' >>> from sympy.core.numbers import Rational >>> isqrt(Rational(-1, 2)) Traceback (most recent call last): ... ValueError: n must be nonnegative
- sympy.core.intfunc.integer_nthroot(y, n)[source]¶
Return a tuple containing x = floor(y**(1/n)) and a boolean indicating whether the result is exact (that is, whether x**n == y).
Examples
>>> from sympy import integer_nthroot >>> integer_nthroot(16, 2) (4, True) >>> integer_nthroot(26, 2) (5, False)
To simply determine if a number is a perfect square, the is_square function should be used:
>>> from sympy.ntheory.primetest import is_square >>> is_square(26) False
See also
- sympy.core.intfunc.integer_log(n, b)[source]¶
Returns
(e, bool)
where e is the largest nonnegative integer such that \(|n| \geq |b^e|\) andbool
is True if \(n = b^e\).Examples
>>> from sympy import integer_log >>> integer_log(125, 5) (3, True) >>> integer_log(17, 9) (1, False)
If the base is positive and the number negative the return value will always be the same except for 2:
>>> integer_log(-4, 2) (2, False) >>> integer_log(-16, 4) (0, False)
When the base is negative, the returned value will only be True if the parity of the exponent is correct for the sign of the base:
>>> integer_log(4, -2) (2, True) >>> integer_log(8, -2) (3, False) >>> integer_log(-8, -2) (3, True) >>> integer_log(-4, -2) (2, False)
- sympy.core.intfunc.mod_inverse(a, m)[source]¶
Return the number \(c\) such that, \(a \times c = 1 \pmod{m}\) where \(c\) has the same sign as \(m\). If no such value exists, a ValueError is raised.
Examples
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse \(x\) of 3 modulo 11. This is the same as finding \(x\) such that \(3x = 1 \pmod{11}\). One value of x that satisfies this congruence is 4. Because \(3 \times 4 = 12\) and \(12 = 1 \pmod{11}\). This is the value returned by
mod_inverse
:>>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7
When there is a common factor between the numerators of \(a\) and \(m\) the inverse does not exist:
>>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2) 7/2
References
numbers¶
- class sympy.core.numbers.Number(*obj)[source]¶
Represents atomic numbers in SymPy.
Explanation
Floating point numbers are represented by the Float class. Rational numbers (of any size) are represented by the Rational class. Integer numbers (of any size) are represented by the Integer class. Float and Rational are subclasses of Number; Integer is a subclass of Rational.
For example,
2/3
is represented asRational(2, 3)
which is a different object from the floating point number obtained with Python division2/3
. Even for numbers that are exactly represented in binary, there is a difference between how two forms, such asRational(1, 2)
andFloat(0.5)
, are used in SymPy. The rational form is to be preferred in symbolic computations.Other kinds of numbers, such as algebraic numbers
sqrt(2)
or complex numbers3 + 4*I
, are not instances of Number class as they are not atomic.
- class sympy.core.numbers.Float(num, dps=None, precision=None)[source]¶
Represent a floating-point number of arbitrary precision.
Examples
>>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000
Creating Floats from strings (and Python
int
andlong
types) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered.>>> Float(1) 1.00000000000000 >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 100000000000000000000.
However, floating-point numbers (Python
float
types) retain only 15 digits of precision:>>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457
It may be preferable to enter high-precision decimal numbers as strings:
>>> Float('1.23456789123456789') 1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e-3', 3) 0.00100 >>> Float(100, 4) 100.0
Float can automatically count significant figures if a null string is sent for the precision; spaces or underscores are also allowed. (Auto- counting is only allowed for strings, ints and longs).
>>> Float('123 456 789.123_456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3.
If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the “e” signifies only how to move the decimal:
>>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00
Notes
Floats are inexact by their nature unless their value is a binary-exact value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision:
>>> approx.evalf(5) 0.099609
By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy:
>>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000
Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the underlying float (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros:
>>> Float(0.3, 20) 0.29999999999999998890
If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python’s float is used:
>>> Float('0.3', 20) 0.30000000000000000000
Although you can increase the precision of an existing Float using Float it will not increase the accuracy – the underlying value is not changed:
>>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10
The same thing happens when evalf is used on a Float:
>>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10
Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p:
>>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000
An actual mpf tuple also contains the number of bits in c as the last element of the tuple:
>>> _._mpf_ (1, 5, 0, 3)
This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks.
In SymPy, a Float is a number that can be computed with arbitrary precision. Although floating point ‘inf’ and ‘nan’ are not such numbers, Float can create these numbers:
>>> Float('-inf') -oo >>> _.is_Float False
Zero in Float only has a single value. Values are not separate for positive and negative zeroes.
- class sympy.core.numbers.Rational(p, q=None, gcd=None)[source]¶
Represents rational numbers (p/q) of any size.
Examples
>>> from sympy import Rational, nsimplify, S, pi >>> Rational(1, 2) 1/2
Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned:
>>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12):
>>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5
An arbitrarily precise Rational is obtained when a string literal is passed:
>>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320
The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify:
>>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10
But if the input does not reduce to a literal Rational, an error will be raised:
>>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi
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.75
If an unevaluated Rational is desired,
gcd=1
can be passed and this will keep common divisors of the numerator and denominator from being eliminated. It is not possible, however, to leave a negative value in the denominator.>>> Rational(2, 4, gcd=1) 2/4 >>> Rational(2, -4, gcd=1).q 4
- as_content_primitive(
- radical=False,
- clear=True,
Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1)
See docstring of Expr.as_content_primitive for more examples.
- class sympy.core.numbers.Integer(i)[source]¶
Represents integer numbers of any size.
Examples
>>> from sympy import Integer >>> Integer(3) 3
If a float or a rational is passed to Integer, the fractional part will be discarded; the effect is of rounding toward zero.
>>> Integer(3.8) 3 >>> Integer(-3.8) -3
A string is acceptable input if it can be parsed as an integer:
>>> Integer("9" * 20) 99999999999999999999
It is rarely needed to explicitly instantiate an Integer, because Python integers are automatically converted to Integer when they are used in SymPy expressions.
- class sympy.core.numbers.AlgebraicNumber(
- expr,
- coeffs=None,
- alias=None,
- **args,
Class for representing algebraic numbers in SymPy.
Symbolically, an instance of this class represents an element \(\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}\). That is, the algebraic number \(\alpha\) is represented as an element of a particular number field \(\mathbb{Q}(\theta)\), with a particular embedding of this field into the complex numbers.
Formally, the primitive element \(\theta\) is given by two data points: (1) its minimal polynomial (which defines \(\mathbb{Q}(\theta)\)), and (2) a particular complex number that is a root of this polynomial (which defines the embedding \(\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}\)). Finally, the algebraic number \(\alpha\) which we represent is then given by the coefficients of a polynomial in \(\theta\).
- static __new__(
- cls,
- expr,
- coeffs=None,
- alias=None,
- **args,
Construct a new algebraic number \(\alpha\) belonging to a number field \(k = \mathbb{Q}(\theta)\).
There are four instance attributes to be determined:
Attribute
Type/Meaning
root
Expr
for \(\theta\) as a complex numberminpoly
Poly
, the minimal polynomial of \(\theta\)rep
DMP
giving \(\alpha\) as poly in \(\theta\)alias
Symbol
for \(\theta\), orNone
See Parameters section for how they are determined.
- Parameters:
expr :
Expr
, or pair \((m, r)\)There are three distinct modes of construction, depending on what is passed as expr.
(1) expr is an
AlgebraicNumber
: In this case we begin by copying all four instance attributes from expr. If coeffs were also given, we compose the two coeff polynomials (see below). If an alias was given, it overrides.(2) expr is any other type of
Expr
: Thenroot
will equal expr. Therefore it must express an algebraic quantity, and we will compute itsminpoly
.(3) expr is an ordered pair \((m, r)\) giving the
minpoly
\(m\), and aroot
\(r\) thereof, which together define \(\theta\). In this case \(m\) may be either a univariatePoly
or anyExpr
which represents the same, while \(r\) must be someExpr
representing a complex number that is a root of \(m\), including both explicit expressions in radicals, and instances ofComplexRootOf
orAlgebraicNumber
.coeffs : list,
ANP
, None, optional (default=None)This defines
rep
, giving the algebraic number \(\alpha\) as a polynomial in \(\theta\).If a list, the elements should be integers or rational numbers. If an
ANP
, we take its coefficients (using itsto_list()
method). IfNone
, then the list of coefficients defaults to[1, 0]
, meaning that \(\alpha = \theta\) is the primitive element of the field.If expr was an
AlgebraicNumber
, let \(g(x)\) be itsrep
polynomial, and let \(f(x)\) be the polynomial defined by coeffs. Thenself.rep
will represent the composition \((f \circ g)(x)\).alias : str,
Symbol
, None, optional (default=None)This is a way to provide a name for the primitive element. We described several ways in which the expr argument can define the value of the primitive element, but none of these methods gave it a name. Here, for example, alias could be set as
Symbol('theta')
, in order to make this symbol appear when \(\alpha\) is printed, or rendered as a polynomial, using theas_poly()
method.
Examples
Recall that we are constructing an algebraic number as a field element \(\alpha \in \mathbb{Q}(\theta)\).
>>> from sympy import AlgebraicNumber, sqrt, CRootOf, S >>> from sympy.abc import x
Example (1): \(\alpha = \theta = \sqrt{2}\)
>>> a1 = AlgebraicNumber(sqrt(2)) >>> a1.minpoly_of_element().as_expr(x) x**2 - 2 >>> a1.evalf(10) 1.414213562
Example (2): \(\alpha = 3 \sqrt{2} - 5\), \(\theta = \sqrt{2}\). We can either build on the last example:
>>> a2 = AlgebraicNumber(a1, [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2)
or start from scratch:
>>> a2 = AlgebraicNumber(sqrt(2), [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2)
Example (3): \(\alpha = 6 \sqrt{2} - 11\), \(\theta = \sqrt{2}\). Again we can build on the previous example, and we see that the coeff polys are composed:
>>> a3 = AlgebraicNumber(a2, [2, -1]) >>> a3.as_expr() -11 + 6*sqrt(2)
reflecting the fact that \((2x - 1) \circ (3x - 5) = 6x - 11\).
Example (4): \(\alpha = \sqrt{2}\), \(\theta = \sqrt{2} + \sqrt{3}\). The easiest way is to use the
to_number_field()
function:>>> from sympy import to_number_field >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) >>> a4.minpoly_of_element().as_expr(x) x**2 - 2 >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) >>> a4.coeffs() [1/2, 0, -9/2, 0]
but if you already knew the right coefficients, you could construct it directly:
>>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3)
Example (5): Construct the Golden Ratio as an element of the 5th cyclotomic field, supposing we already know its coefficients. This time we introduce the alias \(\zeta\) for the primitive element of the field:
>>> from sympy import cyclotomic_poly >>> from sympy.abc import zeta >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), ... [-1, -1, 0, 0], alias=zeta) >>> a5.as_poly().as_expr() -zeta**3 - zeta**2 >>> a5.evalf() 1.61803398874989
(The index
-1
toCRootOf
selects the complex root with the largest real and imaginary parts, which in this case is \(\mathrm{e}^{2i\pi/5}\). SeeComplexRootOf
.)Example (6): Building on the last example, construct the number \(2 \phi \in \mathbb{Q}(\phi)\), where \(\phi\) is the Golden Ratio:
>>> from sympy.abc import phi >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi) >>> a6.as_poly().as_expr() 2*phi >>> a6.primitive_element().evalf() 1.61803398874989
Note that we needed to use
a5.to_root()
, since passinga5
as the first argument would have constructed the number \(2 \phi\) as an element of the field \(\mathbb{Q}(\zeta)\):>>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0]) >>> a6_wrong.as_poly().as_expr() -2*zeta**3 - 2*zeta**2 >>> a6_wrong.primitive_element().evalf() 0.309016994374947 + 0.951056516295154*I
- field_element(coeffs)[source]¶
Form another element of the same number field.
- Parameters:
coeffs : list,
ANP
Like the coeffs arg to the class
constructor
, defines the new element as a polynomial in the primitive element.If a list, the elements should be integers or rational numbers. If an
ANP
, we take its coefficients (using itsto_list()
method).
Explanation
If we represent \(\alpha \in \mathbb{Q}(\theta)\), form another element \(\beta \in \mathbb{Q}(\theta)\) of the same number field.
Examples
>>> from sympy import AlgebraicNumber, sqrt >>> a = AlgebraicNumber(sqrt(5), [-1, 1]) >>> b = a.field_element([3, 2]) >>> print(a) 1 - sqrt(5) >>> print(b) 2 + 3*sqrt(5) >>> print(b.primitive_element() == a.primitive_element()) True
See also
- property is_aliased¶
Returns
True
ifalias
was set.
- property is_primitive_element¶
Say whether this algebraic number \(\alpha \in \mathbb{Q}(\theta)\) is equal to the primitive element \(\theta\) for its field.
- minpoly_of_element()[source]¶
Compute the minimal polynomial for this algebraic number.
Explanation
Recall that we represent an element \(\alpha \in \mathbb{Q}(\theta)\). Our instance attribute
self.minpoly
is the minimal polynomial for our primitive element \(\theta\). This method computes the minimal polynomial for \(\alpha\).
- primitive_element()[source]¶
Get the primitive element \(\theta\) for the number field \(\mathbb{Q}(\theta)\) to which this algebraic number \(\alpha\) belongs.
- Returns:
AlgebraicNumber
- to_primitive_element(
- radicals=True,
Convert
self
to anAlgebraicNumber
instance that is equal to its own primitive element.- Parameters:
radicals : boolean, optional (default=True)
If
True
, then we will try to return anAlgebraicNumber
whoseroot
is an expression in radicals. If that is not possible (or if radicals isFalse
),root
will be aComplexRootOf
.- Returns:
AlgebraicNumber
Explanation
If we represent \(\alpha \in \mathbb{Q}(\theta)\), \(\alpha \neq \theta\), construct a new
AlgebraicNumber
that represents \(\alpha \in \mathbb{Q}(\alpha)\).Examples
>>> from sympy import sqrt, to_number_field >>> from sympy.abc import x >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
The
AlgebraicNumber
a
represents the number \(\sqrt{2}\) in the field \(\mathbb{Q}(\sqrt{2} + \sqrt{3})\). Renderinga
as a polynomial,>>> a.as_poly().as_expr(x) x**3/2 - 9*x/2
reflects the fact that \(\sqrt{2} = \theta^3/2 - 9 \theta/2\), where \(\theta = \sqrt{2} + \sqrt{3}\).
a
is not equal to its own primitive element. Its minpoly>>> a.minpoly.as_poly().as_expr(x) x**4 - 10*x**2 + 1
is that of \(\theta\).
Converting to a primitive element,
>>> a_prim = a.to_primitive_element() >>> a_prim.minpoly.as_poly().as_expr(x) x**2 - 2
we obtain an
AlgebraicNumber
whoseminpoly
is that of the number itself.See also
- to_root(
- radicals=True,
- minpoly=None,
Convert to an
Expr
that is not anAlgebraicNumber
, specifically, either aComplexRootOf
, or, optionally and where possible, an expression in radicals.- Parameters:
radicals : boolean, optional (default=True)
If
True
, then we will try to return the root as an expression in radicals. If that is not possible, we will return aComplexRootOf
.minpoly :
Poly
If the minimal polynomial for \(self\) has been pre-computed, it can be passed in order to save time.
- sympy.core.numbers.seterr(divide=False)[source]¶
Should SymPy raise an exception on 0/0 or return a nan?
divide == True …. raise an exception divide == False … return nan
- class sympy.core.numbers.Zero[source]¶
The number zero.
Zero is a singleton, and can be accessed by
S.Zero
Examples
>>> from sympy import S, Integer >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo
References
- class sympy.core.numbers.One[source]¶
The number one.
One is a singleton, and can be accessed by
S.One
.Examples
>>> from sympy import S, Integer >>> Integer(1) is S.One True
References
- class sympy.core.numbers.NegativeOne[source]¶
The number negative one.
NegativeOne is a singleton, and can be accessed by
S.NegativeOne
.Examples
>>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True
See also
References
- class sympy.core.numbers.Half[source]¶
The rational number 1/2.
Half is a singleton, and can be accessed by
S.Half
.Examples
>>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True
References
- class sympy.core.numbers.NaN[source]¶
Not a Number.
Explanation
This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as
0/0
oroo - oo` produce NaN. Two exceptions are ``0**0
andoo**0
, which all produce1
(this is consistent with Python’s float).NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python
float('nan')
. Differences are noted below.NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counter-intuitive results with
Eq
and==
in the examples below.NaN is not comparable so inequalities raise a TypeError. This is in contrast with floating point nan where all inequalities are false.
NaN is a singleton, and can be accessed by
S.NaN
, or can be imported asnan
.Examples
>>> from sympy import nan, S, oo, Eq >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality False >>> nan == nan # structural equality True
References
- class sympy.core.numbers.Infinity[source]¶
Positive infinite quantity.
Explanation
In real analysis the symbol \(\infty\) denotes an unbounded limit: \(x\to\infty\) means that \(x\) grows without bound.
Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled \(+\infty\) and \(-\infty\) can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers.
Infinity is a singleton, and can be accessed by
S.Infinity
, or can be imported asoo
.Examples
>>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo
See also
References
- class sympy.core.numbers.NegativeInfinity[source]¶
Negative infinite quantity.
NegativeInfinity is a singleton, and can be accessed by
S.NegativeInfinity
.See also
- class sympy.core.numbers.ComplexInfinity[source]¶
Complex infinity.
Explanation
In complex analysis the symbol \(\tilde\infty\), called “complex infinity”, represents a quantity with infinite magnitude, but undetermined complex phase.
ComplexInfinity is a singleton, and can be accessed by
S.ComplexInfinity
, or can be imported aszoo
.Examples
>>> from sympy import zoo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo
See also
- class sympy.core.numbers.Exp1[source]¶
The \(e\) constant.
Explanation
The transcendental number \(e = 2.718281828\ldots\) is the base of the natural logarithm and of the exponential function, \(e = \exp(1)\). Sometimes called Euler’s number or Napier’s constant.
Exp1 is a singleton, and can be accessed by
S.Exp1
, or can be imported asE
.Examples
>>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1
References
- class sympy.core.numbers.ImaginaryUnit[source]¶
The imaginary unit, \(i = \sqrt{-1}\).
I is a singleton, and can be accessed by
S.I
, or can be imported asI
.Examples
>>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I
References
- class sympy.core.numbers.Pi[source]¶
The \(\pi\) constant.
Explanation
The transcendental number \(\pi = 3.141592654\ldots\) represents the ratio of a circle’s circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics.
Pi is a singleton, and can be accessed by
S.Pi
, or can be imported aspi
.Examples
>>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi)
References
- class sympy.core.numbers.EulerGamma[source]¶
The Euler-Mascheroni constant.
Explanation
\(\gamma = 0.5772157\ldots\) (also called Euler’s constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm:
\[\gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)\]EulerGamma is a singleton, and can be accessed by
S.EulerGamma
.Examples
>>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False
References
- class sympy.core.numbers.Catalan[source]¶
Catalan’s constant.
Explanation
\(G = 0.91596559\ldots\) is given by the infinite series
\[G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}\]Catalan is a singleton, and can be accessed by
S.Catalan
.Examples
>>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False
References
- class sympy.core.numbers.GoldenRatio[source]¶
The golden ratio, \(\phi\).
Explanation
\(\phi = \frac{1 + \sqrt{5}}{2}\) is an algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum.
GoldenRatio is a singleton, and can be accessed by
S.GoldenRatio
.Examples
>>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True
References
- class sympy.core.numbers.TribonacciConstant[source]¶
The tribonacci constant.
Explanation
The tribonacci numbers are like the Fibonacci numbers, but instead of starting with two predetermined terms, the sequence starts with three predetermined terms and each term afterwards is the sum of the preceding three terms.
The tribonacci constant is the ratio toward which adjacent tribonacci numbers tend. It is a root of the polynomial \(x^3 - x^2 - x - 1 = 0\), and also satisfies the equation \(x + x^{-3} = 2\).
TribonacciConstant is a singleton, and can be accessed by
S.TribonacciConstant
.Examples
>>> from sympy import S >>> S.TribonacciConstant > 1 True >>> S.TribonacciConstant.expand(func=True) 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3 >>> S.TribonacciConstant.is_irrational True >>> S.TribonacciConstant.n(20) 1.8392867552141611326
References
- sympy.core.numbers.mod_inverse(a, m)[source]¶
Return the number \(c\) such that, \(a \times c = 1 \pmod{m}\) where \(c\) has the same sign as \(m\). If no such value exists, a ValueError is raised.
Examples
>>> from sympy import mod_inverse, S
Suppose we wish to find multiplicative inverse \(x\) of 3 modulo 11. This is the same as finding \(x\) such that \(3x = 1 \pmod{11}\). One value of x that satisfies this congruence is 4. Because \(3 \times 4 = 12\) and \(12 = 1 \pmod{11}\). This is the value returned by
mod_inverse
:>>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7
When there is a common factor between the numerators of \(a\) and \(m\) the inverse does not exist:
>>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(S(2)/7, S(5)/2) 7/2
References
- sympy.core.numbers.equal_valued(x, y)[source]¶
Compare expressions treating plain floats as rationals.
Examples
>>> from sympy import S, symbols, Rational, Float >>> from sympy.core.numbers import equal_valued >>> equal_valued(1, 2) False >>> equal_valued(1, 1) True
In SymPy expressions with Floats compare unequal to corresponding expressions with rationals:
>>> x = symbols('x') >>> x**2 == x**2.0 False
However an individual Float compares equal to a Rational:
>>> Rational(1, 2) == Float(0.5) False
In a future version of SymPy this might change so that Rational and Float compare unequal. This function provides the behavior currently expected of
==
so that it could still be used if the behavior of==
were to change in future.>>> equal_valued(1, 1.0) # Float vs Rational True >>> equal_valued(S(1).n(3), S(1).n(5)) # Floats of different precision True
Explanation
In future SymPy verions Float and Rational might compare unequal and floats with different precisions might compare unequal. In that context a function is needed that can check if a number is equal to 1 or 0 etc. The idea is that instead of testing
if x == 1:
if we want to accept floats like1.0
as well then the test can be written asif equal_valued(x, 1):
orif equal_valued(x, 2):
. Since this function is intended to be used in situations where one or both operands are expected to be concrete numbers like 1 or 0 the function does not recurse through the args of any compound expression to compare any nested floats.References
power¶
- class sympy.core.power.Pow( )[source]¶
Defines the expression x**y as “x raised to a power y”
Deprecated since version 1.7: Using arguments that aren’t subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
expr
value
reason
z**0
1
Although arguments over 0**0 exist, see [2].
z**1
z
(-oo)**(-1)
0
(-1)**-1
-1
S.Zero**-1
zoo
This is not strictly true, as 0**-1 may be undefined, but is convenient in some contexts where the base is assumed to be positive.
1**-1
1
oo**-1
0
0**oo
0
Because for all complex numbers z near 0, z**oo -> 0.
0**-oo
zoo
This is not strictly true, as 0**oo may be oscillating between positive and negative values or rotating in the complex plane. It is convenient, however, when the base is positive.
1**oo 1**-oo
nan
Because there are various cases where lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), but lim( x(t)**y(t), t) != 1. See [3].
b**zoo
nan
Because b**z has no limit as z -> zoo
(-1)**oo (-1)**(-oo)
nan
Because of oscillations in the limit.
oo**oo
oo
oo**-oo
0
(-oo)**oo (-oo)**-oo
nan
oo**I (-oo)**I
nan
oo**e could probably be best thought of as the limit of x**e for real x as x tends to oo. If e is I, then the limit does not exist and nan is used to indicate that.
oo**(1+I) (-oo)**(1+I)
zoo
If the real part of e is positive, then the limit of abs(x**e) is oo. So the limit value is zoo.
oo**(-1+I) -oo**(-1+I)
0
If the real part of e is negative, then the limit is 0.
Because symbolic computations are more flexible than floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra test-case code in the calculation of limits.
References
- as_base_exp()[source]¶
Return base and exp of self.
Explanation
If base a Rational less than 1, then return 1/Rational, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments.
Examples
>>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2) >>> p.base, p.exp (1/2, 2)
- as_content_primitive(
- radical=False,
- clear=True,
Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> from sympy import sqrt >>> sqrt(4 + 4*sqrt(2)).as_content_primitive() (2, sqrt(1 + sqrt(2))) >>> sqrt(3 + 3*sqrt(2)).as_content_primitive() (1, sqrt(3)*sqrt(1 + sqrt(2)))
>>> from sympy import expand_power_base, powsimp, Mul >>> from sympy.abc import x, y
>>> ((2*x + 2)**2).as_content_primitive() (4, (x + 1)**2) >>> (4**((1 + y)/2)).as_content_primitive() (2, 4**(y/2)) >>> (3**((1 + y)/2)).as_content_primitive() (1, 3**((y + 1)/2)) >>> (3**((5 + y)/2)).as_content_primitive() (9, 3**((y + 1)/2)) >>> eq = 3**(2 + 2*x) >>> powsimp(eq) == eq True >>> eq.as_content_primitive() (9, 3**(2*x)) >>> powsimp(Mul(*_)) 3**(2*x + 2)
>>> eq = (2 + 2*x)**y >>> s = expand_power_base(eq); s.is_Mul, s (False, (2*x + 2)**y) >>> eq.as_content_primitive() (1, (2*(x + 1))**y) >>> s = expand_power_base(_[1]); s.is_Mul, s (True, 2**y*(x + 1)**y)
See docstring of Expr.as_content_primitive for more examples.
mul¶
- class sympy.core.mul.Mul(*args, evaluate=None, _sympify=True)[source]¶
Expression representing multiplication operation for algebraic field.
Deprecated since version 1.7: Using arguments that aren’t subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.Every argument of
Mul()
must beExpr
. Infix operator*
on most scalar objects in SymPy calls this class.Another use of
Mul()
is to represent the structure of abstract multiplication so that its arguments can be substituted to return different class. Refer to examples section for this.Mul()
evaluates the argument unlessevaluate=False
is passed. The evaluation logic includes:- Flattening
Mul(x, Mul(y, z))
->Mul(x, y, z)
- Identity removing
Mul(x, 1, y)
->Mul(x, y)
- Exponent collecting by
.as_base_exp()
Mul(x, x**2)
->Pow(x, 3)
- Exponent collecting by
- Term sorting
Mul(y, x, 2)
->Mul(2, x, y)
Since multiplication can be vector space operation, arguments may have the different
sympy.core.kind.Kind()
. Kind of the resulting object is automatically inferred.Examples
>>> from sympy import Mul >>> from sympy.abc import x, y >>> Mul(x, 1) x >>> Mul(x, x) x**2
If
evaluate=False
is passed, result is not evaluated.>>> Mul(1, 2, evaluate=False) 1*2 >>> Mul(x, x, evaluate=False) x*x
Mul()
also represents the general structure of multiplication operation.>>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> expr = Mul(x,y).subs({y:A}) >>> expr x*A >>> type(expr) <class 'sympy.matrices.expressions.matmul.MatMul'>
See also
- as_content_primitive(
- radical=False,
- clear=True,
Return the tuple (R, self/R) where R is the positive Rational extracted from self.
Examples
>>> from sympy import sqrt >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive() (6, -sqrt(2)*(1 - sqrt(2)))
See docstring of Expr.as_content_primitive for more examples.
- as_ordered_factors(order=None)[source]¶
Transform an expression into an ordered list of factors.
Examples
>>> from sympy import sin, cos >>> from sympy.abc import x, y
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors() [2, x, y, sin(x), cos(x)]
- as_two_terms()[source]¶
Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
if you want only the head, use self.args[0];
if you want to process the arguments of the tail then use self.as_coef_mul() which gives the head and a tuple containing the arguments of the tail when treated as a Mul.
if you want the coefficient when self is treated as an Add then use self.as_coeff_add()[0]
Examples
>>> from sympy.abc import x, y >>> (3*x*y).as_two_terms() (3, x*y)
- classmethod flatten(seq)[source]¶
Return commutative, noncommutative and order arguments by combining related terms.
Notes
In an expression like
a*b*c
, Python process this through SymPy asMul(Mul(a, b), c)
. This can have undesirable consequences.Sometimes terms are not combined as one would like: {c.f. https://github.com/sympy/sympy/issues/4596}
>>> from sympy import Mul, sqrt >>> from sympy.abc import x, y, z >>> 2*(x + 1) # this is the 2-arg Mul behavior 2*x + 2 >>> y*(x + 1)*2 2*y*(x + 1) >>> 2*(x + 1)*y # 2-arg result will be obtained first y*(2*x + 2) >>> Mul(2, x + 1, y) # all 3 args simultaneously processed 2*y*(x + 1) >>> 2*((x + 1)*y) # parentheses can control this behavior 2*y*(x + 1)
Powers with compound bases may not find a single base to combine with unless all arguments are processed at once. Post-processing may be necessary in such cases. {c.f. https://github.com/sympy/sympy/issues/5728}
>>> a = sqrt(x*sqrt(y)) >>> a**3 (x*sqrt(y))**(3/2) >>> Mul(a,a,a) (x*sqrt(y))**(3/2) >>> a*a*a x*sqrt(y)*sqrt(x*sqrt(y)) >>> _.subs(a.base, z).subs(z, a.base) (x*sqrt(y))**(3/2)
If more than two terms are being multiplied then all the previous terms will be re-processed for each new argument. So if each of
a
,b
andc
wereMul
expression, thena*b*c
(or building up the product with*=
) will process all the arguments ofa
andb
twice: once whena*b
is computed and again whenc
is multiplied.Using
Mul(a, b, c)
will process all arguments once.
The results of Mul are cached according to arguments, so flatten will only be called once for
Mul(a, b, c)
. If you can structure a calculation so the arguments are most likely to be repeats then this can save time in computing the answer. For example, say you had a Mul, M, that you wished to divide byd[i]
and multiply byn[i]
and you suspect there are many repeats inn
. It would be better to computeM*n[i]/d[i]
rather thanM/d[i]*n[i]
since every time n[i] is a repeat, the product,M*n[i]
will be returned without flattening – the cached value will be returned. If you divide by thed[i]
first (and those are more unique than then[i]
) then that will create a new Mul,M/d[i]
the args of which will be traversed again when it is multiplied byn[i]
.{c.f. https://github.com/sympy/sympy/issues/5706}
This consideration is moot if the cache is turned off.
Nb
The validity of the above notes depends on the implementation details of Mul and flatten which may change at any time. Therefore, you should only consider them when your code is highly performance sensitive.
Removal of 1 from the sequence is already handled by AssocOp.__new__.
- sympy.core.mul.prod(a, start=1)[source]¶
- Return product of elements of a. Start with int 1 so if only
ints are included then an int result is returned.
Examples
>>> from sympy import prod, S >>> prod(range(3)) 0 >>> type(_) is int True >>> prod([S(2), 3]) 6 >>> _.is_Integer True
You can start the product at something other than 1:
>>> prod([1, 2], 3) 6
add¶
- class sympy.core.add.Add(*args, evaluate=None, _sympify=True)[source]¶
Expression representing addition operation for algebraic group.
Deprecated since version 1.7: Using arguments that aren’t subclasses of
Expr
in core operators (Mul
,Add
, andPow
) is deprecated. See Core operators no longer accept non-Expr args for details.Every argument of
Add()
must beExpr
. Infix operator+
on most scalar objects in SymPy calls this class.Another use of
Add()
is to represent the structure of abstract addition so that its arguments can be substituted to return different class. Refer to examples section for this.Add()
evaluates the argument unlessevaluate=False
is passed. The evaluation logic includes:- Flattening
Add(x, Add(y, z))
->Add(x, y, z)
- Identity removing
Add(x, 0, y)
->Add(x, y)
- Coefficient collecting by
.as_coeff_Mul()
Add(x, 2*x)
->Mul(3, x)
- Coefficient collecting by
- Term sorting
Add(y, x, 2)
->Add(2, x, y)
If no argument is passed, identity element 0 is returned. If single element is passed, that element is returned.
Note that
Add(*args)
is more efficient thansum(args)
because it flattens the arguments.sum(a, b, c, ...)
recursively adds the arguments asa + (b + (c + ...))
, which has quadratic complexity. On the other hand,Add(a, b, c, d)
does not assume nested structure, making the complexity linear.Since addition is group operation, every argument should have the same
sympy.core.kind.Kind()
.Examples
>>> from sympy import Add, I >>> from sympy.abc import x, y >>> Add(x, 1) x + 1 >>> Add(x, x) 2*x >>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1 2*x**2 + 17*x/5 + 3.0*y + I*y + 1
If
evaluate=False
is passed, result is not evaluated.>>> Add(1, 2, evaluate=False) 1 + 2 >>> Add(x, x, evaluate=False) x + x
Add()
also represents the general structure of addition operation.>>> from sympy import MatrixSymbol >>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2) >>> expr = Add(x,y).subs({x:A, y:B}) >>> expr A + B >>> type(expr) <class 'sympy.matrices.expressions.matadd.MatAdd'>
Note that the printers do not display in args order.
>>> Add(x, 1) x + 1 >>> Add(x, 1).args (1, x)
See also
- as_coeff_Add(
- rational=False,
- deps=None,
Efficiently extract the coefficient of a summation.
- as_coeff_add(*deps)[source]¶
Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms.
Examples
>>> from sympy.abc import x >>> (7 + 3*x).as_coeff_add() (7, (3*x,)) >>> (7*x).as_coeff_add() (0, (7*x,))
- as_content_primitive(
- radical=False,
- clear=True,
Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression.
Examples
>>> from sympy import sqrt >>> (3 + 3*sqrt(2)).as_content_primitive() (3, 1 + sqrt(2))
Radical content can also be factored out of the primitive:
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5)))
See docstring of Expr.as_content_primitive for more examples.
- as_numer_denom() tuple[Expr, Expr] [source]¶
Decomposes an expression to its numerator part and its denominator part.
Examples
>>> from sympy.abc import x, y, z >>> (x*y/z).as_numer_denom() (x*y, z) >>> (x*(y + 1)/y**7).as_numer_denom() (x*(y + 1), y**7)
See also
- as_real_imag(deep=True, **hints)[source]¶
Return a tuple representing a complex number.
Examples
>>> from sympy import I >>> (7 + 9*I).as_real_imag() (7, 9) >>> ((1 + I)/(1 - I)).as_real_imag() (0, 1) >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag() (-5, 5)
- as_two_terms()[source]¶
Return head and tail of self.
This is the most efficient way to get the head and tail of an expression.
if you want only the head, use self.args[0];
if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add.
if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0]
>>> from sympy.abc import x, y >>> (3*x - 2*y + 5).as_two_terms() (5, 3*x - 2*y)
- extract_leading_order(symbols, point=None)[source]¶
Returns the leading term and its 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)),)
- classmethod flatten(
- seq: list[Expr],
Takes the sequence “seq” of nested Adds and returns a flatten list.
Returns: (commutative_part, noncommutative_part, order_symbols)
Applies associativity, all terms are commutable with respect to addition.
NB: the removal of 0 is already handled by AssocOp.__new__
See also
- primitive()[source]¶
Return
(R, self/R)
whereR`
is the Rational GCD ofself`
.R
is collected only from the leading coefficient of each term.Examples
>>> from sympy.abc import x, y
>>> (2*x + 4*y).primitive() (2, x + 2*y)
>>> (2*x/3 + 4*y/9).primitive() (2/9, 3*x + 2*y)
>>> (2*x/3 + 4.2*y).primitive() (1/3, 2*x + 12.6*y)
No subprocessing of term factors is performed:
>>> ((2 + 2*x)*x + 2).primitive() (1, x*(2*x + 2) + 2)
Recursive processing can be done with the
as_content_primitive()
method:>>> ((2 + 2*x)*x + 2).as_content_primitive() (2, x*(x + 1) + 1)
See also: primitive() function in polytools.py
mod¶
- class sympy.core.mod.Mod(p, q)[source]¶
Represents a modulo operation on symbolic expressions.
- Parameters:
p : Expr
Dividend.
q : Expr
Divisor.
Notes
The convention used is the same as Python’s: the remainder always has the same sign as the divisor.
Many objects can be evaluated modulo
n
much faster than they can be evaluated directly (or at all). For this,evaluate=False
is necessary to prevent eager evaluation:>>> from sympy import binomial, factorial, Mod, Pow >>> Mod(Pow(2, 10**16, evaluate=False), 97) 61 >>> Mod(factorial(10**9, evaluate=False), 10**9 + 9) 712524808 >>> Mod(binomial(10**18, 10**12, evaluate=False), (10**5 + 3)**2) 3744312326
Examples
>>> from sympy.abc import x, y >>> x**2 % y Mod(x**2, y) >>> _.subs({x: 5, y: 6}) 1
relational¶
- class sympy.core.relational.Relational(lhs, rhs, rop=None, **assumptions)[source]¶
Base class for all relation types.
- Parameters:
rop : str or None
Indicates what subclass to instantiate. Valid values can be found in the keys of Relational.ValidRelationOperator.
Explanation
Subclasses of Relational should generally be instantiated directly, but Relational can be instantiated with a valid
rop
value to dispatch to the appropriate subclass.Examples
>>> from sympy import Rel >>> from sympy.abc import x, y >>> Rel(y, x + x**2, '==') Eq(y, x**2 + x)
A relation’s type can be defined upon creation using
rop
. The relation type of an existing expression can be obtained using itsrel_op
property. Here is a table of all the relation types, along with theirrop
andrel_op
values:Relation
rop
rel_op
Equality
==
oreq
orNone
==
Unequality
!=
orne
!=
GreaterThan
>=
orge
>=
LessThan
<=
orle
<=
StrictGreaterThan
>
orgt
>
StrictLessThan
<
orlt
<
For example, setting
rop
to==
produces anEquality
relation,Eq()
. So does settingrop
toeq
, or leavingrop
unspecified. That is, the first threeRel()
below all produce the same result. Using arop
from a different row in the table produces a different relation type. For example, the fourthRel()
below usinglt
forrop
produces aStrictLessThan
inequality:>>> from sympy import Rel >>> from sympy.abc import x, y >>> Rel(y, x + x**2, '==') Eq(y, x**2 + x) >>> Rel(y, x + x**2, 'eq') Eq(y, x**2 + x) >>> Rel(y, x + x**2) Eq(y, x**2 + x) >>> Rel(y, x + x**2, 'lt') y < x**2 + x
To obtain the relation type of an existing expression, get its
rel_op
property. For example,rel_op
is==
for theEquality
relation above, and<
for the strict less than inequality above:>>> from sympy import Rel >>> from sympy.abc import x, y >>> my_equality = Rel(y, x + x**2, '==') >>> my_equality.rel_op '==' >>> my_inequality = Rel(y, x + x**2, 'lt') >>> my_inequality.rel_op '<'
- property canonical¶
Return a canonical form of the relational by putting a number on the rhs, canonically removing a sign or else ordering the args canonically. No other simplification is attempted.
Examples
>>> from sympy.abc import x, y >>> x < 2 x < 2 >>> _.reversed.canonical x < 2 >>> (-y < x).canonical x > -y >>> (-y > x).canonical x < -y >>> (-y < -x).canonical x < y
The canonicalization is recursively applied:
>>> from sympy import Eq >>> Eq(x < y, y > x).canonical True
- equals(other, failing_expression=False)[source]¶
Return True if the sides of the relationship are mathematically identical and the type of relationship is the same. If failing_expression is True, return the expression whose truth value was unknown.
- property lhs¶
The left-hand side of the relation.
- property negated¶
Return the negated relationship.
Examples
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.negated Ne(x, 1) >>> x < 1 x < 1 >>> _.negated x >= 1
Notes
This works more or less identical to
~
/Not
. The difference is thatnegated
returns the relationship even ifevaluate=False
. Hence, this is useful in code when checking for e.g. negated relations to existing ones as it will not be affected by the \(evaluate\) flag.
- property reversed¶
Return the relationship with sides reversed.
Examples
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.reversed Eq(1, x) >>> x < 1 x < 1 >>> _.reversed 1 > x
- property reversedsign¶
Return the relationship with signs reversed.
Examples
>>> from sympy import Eq >>> from sympy.abc import x >>> Eq(x, 1) Eq(x, 1) >>> _.reversedsign Eq(-x, -1) >>> x < 1 x < 1 >>> _.reversedsign -x > -1
- property rhs¶
The right-hand side of the relation.
- property strict¶
return the strict version of the inequality or self
Examples
>>> from sympy.abc import x >>> (x <= 1).strict x < 1 >>> _.strict x < 1
- property weak¶
return the non-strict version of the inequality or self
Examples
>>> from sympy.abc import x >>> (x < 1).weak x <= 1 >>> _.weak x <= 1
- sympy.core.relational.Rel[source]¶
alias of
Relational
- sympy.core.relational.Ne[source]¶
alias of
Unequality
- sympy.core.relational.Lt[source]¶
alias of
StrictLessThan
- sympy.core.relational.Gt[source]¶
alias of
StrictGreaterThan
- sympy.core.relational.Ge[source]¶
alias of
GreaterThan
- class sympy.core.relational.Equality(lhs, rhs, **options)[source]¶
An equal relation between two objects.
Explanation
Represents that two objects are equal. If they can be easily shown to be definitively equal (or unequal), this will reduce to True (or False). Otherwise, the relation is maintained as an unevaluated Equality object. Use the
simplify
function on this object for more nontrivial evaluation of the equality relation.As usual, the keyword argument
evaluate=False
can be used to prevent any evaluation.Examples
>>> from sympy import Eq, simplify, exp, cos >>> from sympy.abc import x, y >>> Eq(y, x + x**2) Eq(y, x**2 + x) >>> Eq(2, 5) False >>> Eq(2, 5, evaluate=False) Eq(2, 5) >>> _.doit() False >>> Eq(exp(x), exp(x).rewrite(cos)) Eq(exp(x), sinh(x) + cosh(x)) >>> simplify(_) True
Notes
Python treats 1 and True (and 0 and False) as being equal; SymPy does not. And integer will always compare as unequal to a Boolean:
>>> Eq(True, 1), True == 1 (False, True)
This class is not the same as the == operator. The == operator tests for exact structural equality between two expressions; this class compares expressions mathematically.
If either object defines an
_eval_Eq
method, it can be used in place of the default algorithm. Iflhs._eval_Eq(rhs)
orrhs._eval_Eq(lhs)
returns anything other than None, that return value will be substituted for the Equality. If None is returned by_eval_Eq
, an Equality object will be created as usual.Since this object is already an expression, it does not respond to the method
as_expr
if one tries to create \(x - y\) fromEq(x, y)
. Ifeq = Eq(x, y)
then write \(eq.lhs - eq.rhs\) to getx - y
.Deprecated since version 1.5:
Eq(expr)
with a single argument is a shorthand forEq(expr, 0)
, but this behavior is deprecated and will be removed in a future version of SymPy.See also
sympy.logic.boolalg.Equivalent
for representing equality between two boolean expressions
- class sympy.core.relational.GreaterThan(lhs, rhs, **options)[source]¶
Class representations of inequalities.
Explanation
The
*Than
classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:lhs \(\ge\) rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
All classes take two arguments, lhs and rhs.
Signature Example
Math Equivalent
GreaterThan(lhs, rhs)
lhs \(\ge\) rhs
LessThan(lhs, rhs)
lhs \(\le\) rhs
StrictGreaterThan(lhs, rhs)
lhs \(>\) rhs
StrictLessThan(lhs, rhs)
lhs \(<\) rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
Notes
There are a couple of “gotchas” to be aware of when using Python’s operators.
The first is that what your write is not always what you get:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways:
“sympify” the literal before comparison
>>> S(1) < x 1 < x
(2) use one of the wrappers or less succinct methods described above
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
The second gotcha involves writing equality tests between relationals when one or both sides of the test involve a literal relational:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
The solution for this case is to wrap literal relationals in parentheses:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R146], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
Although this can also be done with the ‘&’ operator, it cannot be done with the ‘and’ operarator:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R146]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the –Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x > y > z
(x > y) and (y > z)
(GreaterThanObject) and (y > z)
(GreaterThanObject.__bool__()) and (y > z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object’s__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.In Python, there is no way to override the
and
operator, or to control how it short circuits, so it is impossible to make something likex > y > z
work. There was a PEP to change this, PEP 335, but it was officially closed in March, 2012.
- class sympy.core.relational.LessThan(lhs, rhs, **options)[source]¶
Class representations of inequalities.
Explanation
The
*Than
classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:lhs \(\ge\) rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
All classes take two arguments, lhs and rhs.
Signature Example
Math Equivalent
GreaterThan(lhs, rhs)
lhs \(\ge\) rhs
LessThan(lhs, rhs)
lhs \(\le\) rhs
StrictGreaterThan(lhs, rhs)
lhs \(>\) rhs
StrictLessThan(lhs, rhs)
lhs \(<\) rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
Notes
There are a couple of “gotchas” to be aware of when using Python’s operators.
The first is that what your write is not always what you get:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways:
“sympify” the literal before comparison
>>> S(1) < x 1 < x
(2) use one of the wrappers or less succinct methods described above
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
The second gotcha involves writing equality tests between relationals when one or both sides of the test involve a literal relational:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
The solution for this case is to wrap literal relationals in parentheses:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R147], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
Although this can also be done with the ‘&’ operator, it cannot be done with the ‘and’ operarator:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R147]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the –Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x > y > z
(x > y) and (y > z)
(GreaterThanObject) and (y > z)
(GreaterThanObject.__bool__()) and (y > z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object’s__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.In Python, there is no way to override the
and
operator, or to control how it short circuits, so it is impossible to make something likex > y > z
work. There was a PEP to change this, PEP 335, but it was officially closed in March, 2012.
- class sympy.core.relational.Unequality(lhs, rhs, **options)[source]¶
An unequal relation between two objects.
Explanation
Represents that two objects are not equal. If they can be shown to be definitively equal, this will reduce to False; if definitively unequal, this will reduce to True. Otherwise, the relation is maintained as an Unequality object.
Examples
>>> from sympy import Ne >>> from sympy.abc import x, y >>> Ne(y, x+x**2) Ne(y, x**2 + x)
Notes
This class is not the same as the != operator. The != operator tests for exact structural equality between two expressions; this class compares expressions mathematically.
This class is effectively the inverse of Equality. As such, it uses the same algorithms, including any available \(_eval_Eq\) methods.
See also
- class sympy.core.relational.StrictGreaterThan(lhs, rhs, **options)[source]¶
Class representations of inequalities.
Explanation
The
*Than
classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:lhs \(\ge\) rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
All classes take two arguments, lhs and rhs.
Signature Example
Math Equivalent
GreaterThan(lhs, rhs)
lhs \(\ge\) rhs
LessThan(lhs, rhs)
lhs \(\le\) rhs
StrictGreaterThan(lhs, rhs)
lhs \(>\) rhs
StrictLessThan(lhs, rhs)
lhs \(<\) rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
Notes
There are a couple of “gotchas” to be aware of when using Python’s operators.
The first is that what your write is not always what you get:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways:
“sympify” the literal before comparison
>>> S(1) < x 1 < x
(2) use one of the wrappers or less succinct methods described above
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
The second gotcha involves writing equality tests between relationals when one or both sides of the test involve a literal relational:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
The solution for this case is to wrap literal relationals in parentheses:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R148], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
Although this can also be done with the ‘&’ operator, it cannot be done with the ‘and’ operarator:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R148]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the –Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x > y > z
(x > y) and (y > z)
(GreaterThanObject) and (y > z)
(GreaterThanObject.__bool__()) and (y > z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object’s__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.In Python, there is no way to override the
and
operator, or to control how it short circuits, so it is impossible to make something likex > y > z
work. There was a PEP to change this, PEP 335, but it was officially closed in March, 2012.
- class sympy.core.relational.StrictLessThan(lhs, rhs, **options)[source]¶
Class representations of inequalities.
Explanation
The
*Than
classes represent inequal relationships, where the left-hand side is generally bigger or smaller than the right-hand side. For example, the GreaterThan class represents an inequal relationship where the left-hand side is at least as big as the right side, if not bigger. In mathematical notation:lhs \(\ge\) rhs
In total, there are four
*Than
classes, to represent the four inequalities:Class Name
Symbol
GreaterThan
>=
LessThan
<=
StrictGreaterThan
>
StrictLessThan
<
All classes take two arguments, lhs and rhs.
Signature Example
Math Equivalent
GreaterThan(lhs, rhs)
lhs \(\ge\) rhs
LessThan(lhs, rhs)
lhs \(\le\) rhs
StrictGreaterThan(lhs, rhs)
lhs \(>\) rhs
StrictLessThan(lhs, rhs)
lhs \(<\) rhs
In addition to the normal .lhs and .rhs of Relations,
*Than
inequality objects also have the .lts and .gts properties, which represent the “less than side” and “greater than side” of the operator. Use of .lts and .gts in an algorithm rather than .lhs and .rhs as an assumption of inequality direction will make more explicit the intent of a certain section of code, and will make it similarly more robust to client code changes:>>> from sympy import GreaterThan, StrictGreaterThan >>> from sympy import LessThan, StrictLessThan >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S >>> from sympy.abc import x, y, z >>> from sympy.core.relational import Relational
>>> e = GreaterThan(x, 1) >>> e x >= 1 >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts) 'x >= 1 is the same as 1 <= x'
Examples
One generally does not instantiate these classes directly, but uses various convenience methods:
>>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers ... print(f(x, 2)) x >= 2 x > 2 x <= 2 x < 2
Another option is to use the Python inequality operators (
>=
,>
,<=
,<
) directly. Their main advantage over theGe
,Gt
,Le
, andLt
counterparts, is that one can write a more “mathematical looking” statement rather than littering the math with oddball function calls. However there are certain (minor) caveats of which to be aware (search for ‘gotcha’, below).>>> x >= 2 x >= 2 >>> _ == Ge(x, 2) True
However, it is also perfectly valid to instantiate a
*Than
class less succinctly and less conveniently:>>> Rel(x, 1, ">") x > 1 >>> Relational(x, 1, ">") x > 1
>>> StrictGreaterThan(x, 1) x > 1 >>> GreaterThan(x, 1) x >= 1 >>> LessThan(x, 1) x <= 1 >>> StrictLessThan(x, 1) x < 1
Notes
There are a couple of “gotchas” to be aware of when using Python’s operators.
The first is that what your write is not always what you get:
>>> 1 < x x > 1
Due to the order that Python parses a statement, it may not immediately find two objects comparable. When
1 < x
is evaluated, Python recognizes that the number 1 is a native number and that x is not. Because a native Python number does not know how to compare itself with a SymPy object Python will try the reflective operation,x > 1
and that is the form that gets evaluated, hence returned.If the order of the statement is important (for visual output to the console, perhaps), one can work around this annoyance in a couple ways:
“sympify” the literal before comparison
>>> S(1) < x 1 < x
(2) use one of the wrappers or less succinct methods described above
>>> Lt(1, x) 1 < x >>> Relational(1, x, "<") 1 < x
The second gotcha involves writing equality tests between relationals when one or both sides of the test involve a literal relational:
>>> e = x < 1; e x < 1 >>> e == e # neither side is a literal True >>> e == x < 1 # expecting True, too False >>> e != x < 1 # expecting False x < 1 >>> x < 1 != x < 1 # expecting False or the same thing as before Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
The solution for this case is to wrap literal relationals in parentheses:
>>> e == (x < 1) True >>> e != (x < 1) False >>> (x < 1) != (x < 1) False
The third gotcha involves chained inequalities not involving
==
or!=
. Occasionally, one may be tempted to write:>>> e = x < y < z Traceback (most recent call last): ... TypeError: symbolic boolean expression has no truth value.
Due to an implementation detail or decision of Python [R149], there is no way for SymPy to create a chained inequality with that syntax so one must use And:
>>> e = And(x < y, y < z) >>> type( e ) And >>> e (x < y) & (y < z)
Although this can also be done with the ‘&’ operator, it cannot be done with the ‘and’ operarator:
>>> (x < y) & (y < z) (x < y) & (y < z) >>> (x < y) and (y < z) Traceback (most recent call last): ... TypeError: cannot determine truth value of Relational
[R149]This implementation detail is that Python provides no reliable method to determine that a chained inequality is being built. Chained comparison operators are evaluated pairwise, using “and” logic (see https://docs.python.org/3/reference/expressions.html#not-in). This is done in an efficient way, so that each object being compared is only evaluated once and the comparison can short-circuit. For example,
1 > 2 > 3
is evaluated by Python as(1 > 2) and (2 > 3)
. Theand
operator coerces each side into a bool, returning the object itself when it short-circuits. The bool of the –Than operators will raise TypeError on purpose, because SymPy cannot determine the mathematical ordering of symbolic expressions. Thus, if we were to computex > y > z
, withx
,y
, andz
being Symbols, Python converts the statement (roughly) into these steps:x > y > z
(x > y) and (y > z)
(GreaterThanObject) and (y > z)
(GreaterThanObject.__bool__()) and (y > z)
TypeError
Because of the
and
added at step 2, the statement gets turned into a weak ternary statement, and the first object’s__bool__
method will raise TypeError. Thus, creating a chained inequality is not possible.In Python, there is no way to override the
and
operator, or to control how it short circuits, so it is impossible to make something likex > y > z
work. There was a PEP to change this, PEP 335, but it was officially closed in March, 2012.
multidimensional¶
- class sympy.core.multidimensional.vectorize(*mdargs)[source]¶
Generalizes a function taking scalars to accept multidimensional arguments.
Examples
>>> from sympy import vectorize, diff, sin, symbols, Function >>> x, y, z = symbols('x y z') >>> f, g, h = list(map(Function, 'fgh'))
>>> @vectorize(0) ... def vsin(x): ... return sin(x)
>>> vsin([1, x, y]) [sin(1), sin(x), sin(y)]
>>> @vectorize(0, 1) ... def vdiff(f, y): ... return diff(f, y)
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z]) [[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
function¶
- class sympy.core.function.Lambda(signature, expr)[source]¶
Lambda(x, expr) represents a lambda function similar to Python’s ‘lambda x: expr’. A function of several variables is written as Lambda((x, y, …), expr).
Examples
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
It is also possible to unpack tuple arguments:
>>> f = Lambda(((x, y), z), x + y + z) >>> f((1, 2), 3) 6
A handy shortcut for lots of arguments:
>>> p = x, y, z >>> f = Lambda(p, x + y*z) >>> f(*p) x + y*z
- property bound_symbols¶
The variables used in the internal representation of the function
- property expr¶
The return value of the function
- property is_identity¶
Return
True
if thisLambda
is an identity function.
- property signature¶
The expected form of the arguments to be unpacked into variables
- property variables¶
The variables used in the internal representation of the function
- class sympy.core.function.WildFunction(*args)[source]¶
A WildFunction function matches any function (with its arguments).
Examples
>>> from sympy import WildFunction, Function, cos >>> from sympy.abc import x, y >>> F = WildFunction('F') >>> f = Function('f') >>> F.nargs Naturals0 >>> x.match(F) >>> F.match(F) {F_: F_} >>> f(x).match(F) {F_: f(x)} >>> cos(x).match(F) {F_: cos(x)} >>> f(x, y).match(F) {F_: f(x, y)}
To match functions with a given number of arguments, set
nargs
to the desired value at instantiation:>>> F = WildFunction('F', nargs=2) >>> F.nargs {2} >>> f(x).match(F) >>> f(x, y).match(F) {F_: f(x, y)}
To match functions with a range of arguments, set
nargs
to a tuple containing the desired number of arguments, e.g. ifnargs = (1, 2)
then functions with 1 or 2 arguments will be matched.>>> F = WildFunction('F', nargs=(1, 2)) >>> F.nargs {1, 2} >>> f(x).match(F) {F_: f(x)} >>> f(x, y).match(F) {F_: f(x, y)} >>> f(x, y, 1).match(F)
- class sympy.core.function.Derivative(expr, *variables, **kwargs)[source]¶
Carries out differentiation of the given expression with respect to symbols.
Examples
>>> from sympy import Derivative, Function, symbols, Subs >>> from sympy.abc import x, y >>> f, g = symbols('f g', cls=Function)
>>> Derivative(x**2, x, evaluate=True) 2*x
Denesting of derivatives retains the ordering of variables:
>>> Derivative(Derivative(f(x, y), y), x) Derivative(f(x, y), y, x)
Contiguously identical symbols are merged into a tuple giving the symbol and the count:
>>> Derivative(f(x), x, x, y, x) Derivative(f(x), (x, 2), y, x)
If the derivative cannot be performed, and evaluate is True, the order of the variables of differentiation will be made canonical:
>>> Derivative(f(x, y), y, x, evaluate=True) Derivative(f(x, y), x, y)
Derivatives with respect to undefined functions can be calculated:
>>> Derivative(f(x)**2, f(x), evaluate=True) 2*f(x)
Such derivatives will show up when the chain rule is used to evalulate a derivative:
>>> f(g(x)).diff(x) Derivative(f(g(x)), g(x))*Derivative(g(x), x)
Substitution is used to represent derivatives of functions with arguments that are not symbols or functions:
>>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3) True
Notes
Simplification of high-order derivatives:
Because there can be a significant amount of simplification that can be done when multiple differentiations are performed, results will be automatically simplified in a fairly conservative fashion unless the keyword
simplify
is set to False.>>> from sympy import sqrt, diff, Function, symbols >>> from sympy.abc import x, y, z >>> f, g = symbols('f,g', cls=Function)
>>> e = sqrt((x + 1)**2 + x) >>> diff(e, (x, 5), simplify=False).count_ops() 136 >>> diff(e, (x, 5)).count_ops() 30
Ordering of variables:
If evaluate is set to True and the expression cannot 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.
Derivative wrt non-Symbols:
For the most part, one may not differentiate wrt non-symbols. For example, we do not allow differentiation wrt \(x*y\) because there are multiple ways of structurally defining where x*y appears in an expression: a very strict definition would make (x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like cos(x)) are not allowed, either:
>>> (x*y*z).diff(x*y) Traceback (most recent call last): ... ValueError: Can't calculate derivative wrt x*y.
To make it easier to work with variational calculus, however, derivatives wrt AppliedUndef and Derivatives are allowed. For example, in the Euler-Lagrange method one may write F(t, u, v) where u = f(t) and v = f’(t). These variables can be written explicitly as functions of time:
>>> from sympy.abc import t >>> F = Function('F') >>> U = f(t) >>> V = U.diff(t)
The derivative wrt f(t) can be obtained directly:
>>> direct = F(t, U, V).diff(U)
When differentiation wrt a non-Symbol is attempted, the non-Symbol is temporarily converted to a Symbol while the differentiation is performed and the same answer is obtained:
>>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U) >>> assert direct == indirect
The implication of this non-symbol replacement is that all functions are treated as independent of other functions and the symbols are independent of the functions that contain them:
>>> x.diff(f(x)) 0 >>> g(x).diff(f(x)) 0
It also means that derivatives are assumed to depend only on the variables of differentiation, not on anything contained within the expression being differentiated:
>>> F = f(x) >>> Fx = F.diff(x) >>> Fx.diff(F) # derivative depends on x, not F 0 >>> Fxx = Fx.diff(x) >>> Fxx.diff(Fx) # derivative depends on x, not Fx 0
The last example can be made explicit by showing the replacement of Fx in Fxx with y:
>>> Fxx.subs(Fx, y) Derivative(y, x)
Since that in itself will evaluate to zero, differentiating wrt Fx will also be zero:
>>> _.doit() 0
Replacing undefined functions with concrete expressions
One must be careful to replace undefined functions with expressions that contain variables consistent with the function definition and the variables of differentiation or else insconsistent result will be obtained. Consider the following example:
>>> eq = f(x)*g(y) >>> eq.subs(f(x), x*y).diff(x, y).doit() y*Derivative(g(y), y) + g(y) >>> eq.diff(x, y).subs(f(x), x*y).doit() y*Derivative(g(y), y)
The results differ because \(f(x)\) was replaced with an expression that involved both variables of differentiation. In the abstract case, differentiation of \(f(x)\) by \(y\) is 0; in the concrete case, the presence of \(y\) made that derivative nonvanishing and produced the extra \(g(y)\) term.
Defining differentiation for an object
An object 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.
Any class can allow derivatives to be taken with respect to itself (while indicating its scalar nature). See the docstring of Expr._diff_wrt.
See also
- property _diff_wrt¶
An expression may be differentiated wrt a Derivative if it is in elementary form.
Examples
>>> from sympy import Function, Derivative, cos >>> from sympy.abc import x >>> f = Function('f')
>>> Derivative(f(x), x)._diff_wrt True >>> Derivative(cos(x), x)._diff_wrt False >>> Derivative(x + 1, x)._diff_wrt False
A Derivative might be an unevaluated form of what will not be a valid variable of differentiation if evaluated. For example,
>>> Derivative(f(f(x)), x).doit() Derivative(f(x), x)*Derivative(f(f(x)), f(x))
Such an expression will present the same ambiguities as arise when dealing with any other product, like
2*x
, so_diff_wrt
is False:>>> Derivative(f(f(x)), x)._diff_wrt False
- classmethod _sort_variable_count(vc)[source]¶
Sort (variable, count) pairs into canonical order while retaining order of variables that do not commute during differentiation:
symbols and functions commute with each other
derivatives commute with each other
a derivative does not commute with anything it contains
any other object is not allowed to commute if it has free symbols in common with another object
Examples
>>> from sympy import Derivative, Function, symbols >>> vsort = Derivative._sort_variable_count >>> x, y, z = symbols('x y z') >>> f, g, h = symbols('f g h', cls=Function)
Contiguous items are collapsed into one pair:
>>> vsort([(x, 1), (x, 1)]) [(x, 2)] >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) [(y, 2), (f(x), 2)]
Ordering is canonical.
>>> def vsort0(*v): ... # docstring helper to ... # change vi -> (vi, 0), sort, and return vi vals ... return [i[0] for i in vsort([(i, 0) for i in v])]
>>> vsort0(y, x) [x, y] >>> vsort0(g(y), g(x), f(y)) [f(y), g(x), g(y)]
Symbols are sorted as far to the left as possible but never move to the left of a derivative having the same symbol in its variables; the same applies to AppliedUndef which are always sorted after Symbols:
>>> dfx = f(x).diff(x) >>> assert vsort0(dfx, y) == [y, dfx] >>> assert vsort0(dfx, x) == [dfx, x]
- as_finite_difference(
- points=1,
- x0=None,
- wrt=None,
Expresses a Derivative instance as a finite difference.
- Parameters:
points : sequence or coefficient, optional
If sequence: discrete values (length >= order+1) of the independent variable used for generating the finite difference weights. If it is a coefficient, it will be used as the step-size for generating an equidistant sequence of length order+1 centered around
x0
. Default: 1 (step-size 1)x0 : number or Symbol, optional
the value of the independent variable (
wrt
) at which the derivative is to be approximated. Default: same aswrt
.wrt : Symbol, optional
“with respect to” the variable for which the (partial) derivative is to be approximated for. If not provided it is required that the derivative is ordinary. Default:
None
.
Examples
>>> from sympy import symbols, Function, exp, sqrt, Symbol >>> x, h = symbols('x h') >>> f = Function('f') >>> f(x).diff(x).as_finite_difference() -f(x - 1/2) + f(x + 1/2)
The default step size and number of points are 1 and
order + 1
respectively. We can change the step size by passing a symbol as a parameter:>>> f(x).diff(x).as_finite_difference(h) -f(-h/2 + x)/h + f(h/2 + x)/h
We can also specify the discretized values to be used in a sequence:
>>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h]) -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
The algorithm is not restricted to use equidistant spacing, nor do we need to make the approximation around
x0
, but we can get an expression estimating the derivative at an offset:>>> e, sq2 = exp(1), sqrt(2) >>> xl = [x-h, x+h, x+e*h] >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/...
To approximate
Derivative
aroundx0
using a non-equidistant spacing step, the algorithm supports assignment of undefined functions topoints
:>>> dx = Function('dx') >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h) -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x)
Partial derivatives are also supported:
>>> y = Symbol('y') >>> d2fdxdy=f(x,y).diff(x,y) >>> d2fdxdy.as_finite_difference(wrt=x) -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
We can apply
as_finite_difference
toDerivative
instances in compound expressions usingreplace
:>>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative, ... lambda arg: arg.as_finite_difference()) 42**(-f(x - 1/2) + f(x + 1/2)) + 1
- sympy.core.function.diff(f, *symbols, **kwargs)[source]¶
Differentiate f with respect to symbols.
Explanation
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, 3)) >>> diff(f(x), x, 3) Derivative(f(x), (x, 3)) >>> 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.References
- class sympy.core.function.FunctionClass(*args, **kwargs)[source]¶
Base class for function classes. FunctionClass is a subclass of type.
Use Function(‘<function name>’ [ , signature ]) to create undefined function classes.
- property nargs¶
Return a set of the allowed number of arguments for the function.
Examples
>>> from sympy import Function >>> f = Function('f')
If the function can take any number of arguments, the set of whole numbers is returned:
>>> Function('f').nargs Naturals0
If the function was initialized to accept one or more arguments, a corresponding set will be returned:
>>> Function('f', nargs=1).nargs {1} >>> Function('f', nargs=(2, 1)).nargs {1, 2}
The undefined function, after application, also has the nargs attribute; the actual number of arguments is always available by checking the
args
attribute:>>> f = Function('f') >>> f(1).nargs Naturals0 >>> len(f(1).args) 1
- class sympy.core.function.Function(*args)[source]¶
Base class for applied mathematical functions.
It also serves as a constructor for undefined function classes.
See the Writing Custom Functions guide for details on how to subclass
Function
and what methods can be defined.Examples
Undefined Functions
To create an undefined function, pass a string of the function name to
Function
.>>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> g = Function('g')(x) >>> f f >>> f(x) f(x) >>> g g(x) >>> f(x).diff(x) Derivative(f(x), x) >>> g.diff(x) Derivative(g(x), x)
Assumptions can be passed to
Function
the same as with aSymbol
. Alternatively, you can use aSymbol
with assumptions for the function name and the function will inherit the name and assumptions associated with theSymbol
:>>> f_real = Function('f', real=True) >>> f_real(x).is_real True >>> f_real_inherit = Function(Symbol('f', real=True)) >>> f_real_inherit(x).is_real True
Note that assumptions on a function are unrelated to the assumptions on the variables it is called on. If you want to add a relationship, subclass
Function
and define custom assumptions handler methods. See the Assumptions section of the Writing Custom Functions guide for more details.Custom Function Subclasses
The Writing Custom Functions guide has several Complete Examples of how to subclass
Function
to create a custom function.
Note
Not all functions are the same
SymPy defines many functions (like cos
and factorial
). It also
allows the user to create generic functions which act as argument
holders. Such functions are created just like symbols:
>>> from sympy import Function, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> f(2) + f(x)
f(2) + f(x)
If you want to see which functions appear in an expression you can use the atoms method:
>>> e = (f(x) + cos(x) + 2)
>>> e.atoms(Function)
{f(x), cos(x)}
If you just want the function you defined, not SymPy functions, the thing to search for is AppliedUndef:
>>> from sympy.core.function import AppliedUndef
>>> e.atoms(AppliedUndef)
{f(x)}
- class sympy.core.function.Subs(expr, variables, point, **assumptions)[source]¶
Represents unevaluated substitutions of an expression.
Subs(expr, x, x0)
represents the expression resulting from substituting x with x0 in expr.- Parameters:
expr : Expr
An expression.
x : tuple, variable
A variable or list of distinct variables.
x0 : tuple or list of tuples
A point or list of evaluation points corresponding to those variables.
Examples
>>> from sympy import Subs, Function, sin, cos >>> from sympy.abc import x, y, z >>> f = Function('f')
Subs are created when a particular substitution cannot be made. The x in the derivative cannot be replaced with 0 because 0 is not a valid variables of differentiation:
>>> f(x).diff(x).subs(x, 0) Subs(Derivative(f(x), x), x, 0)
Once f is known, the derivative and evaluation at 0 can be done:
>>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) True
Subs can also be created directly with one or more 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)
Notes
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()).
In order to allow expressions to combine before doit is done, a representation of the Subs expression is used internally to make expressions that are superficially different compare the same:
>>> a, b = Subs(x, x, 0), Subs(y, y, 0) >>> a + b 2*Subs(x, x, 0)
This can lead to unexpected consequences when using methods like \(has\) that are cached:
>>> s = Subs(x, x, 0) >>> s.has(x), s.has(y) (True, False) >>> ss = s.subs(x, y) >>> ss.has(x), ss.has(y) (True, False) >>> s, ss (Subs(x, x, 0), Subs(y, y, 0))
- property bound_symbols¶
The variables to be evaluated
- property expr¶
The expression on which the substitution operates
- property point¶
The values for which the variables are to be substituted
- property variables¶
The variables to be evaluated
- sympy.core.function.expand(
- e,
- deep=True,
- modulus=None,
- power_base=True,
- power_exp=True,
- mul=True,
- log=True,
- multinomial=True,
- basic=True,
- **hints,
Expand an expression using methods given as hints.
Explanation
Hints evaluated unless explicitly set to False are:
basic
,log
,multinomial
,mul
,power_base
, andpower_exp
The following hints are supported but not applied unless set to True:complex
,func
, andtrig
. In addition, the following meta-hints are supported by some or all of the other hints:frac
,numer
,denom
,modulus
, andforce
.deep
is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints.The
basic
hint is used for any special rewriting of an object that should be done automatically (along with the other hints likemul
) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the_eval_expand_basic
method. Objects may also define their own expand methods, which are not run by default. See the API section below.If
deep
is set toTrue
(the default), things like arguments of functions are recursively expanded. Usedeep=False
to only expand on the top level.If the
force
hint is used, assumptions about variables will be ignored in making the expansion.Hints
These hints are run by default
Mul
Distributes multiplication over addition:
>>> from sympy import cos, exp, sin >>> from sympy.abc import x, y, z >>> (y*(x + z)).expand(mul=True) x*y + y*z
Multinomial
Expand (x + y + …)**n where n is a positive integer.
>>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
Power_exp
Expand addition in exponents into multiplied bases.
>>> exp(x + y).expand(power_exp=True) exp(x)*exp(y) >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y
Power_base
Split powers of multiplied bases.
This only happens by default if assumptions allow, or if the
force
meta-hint is used:>>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z
Note that in some cases where this expansion always holds, SymPy performs it automatically:
>>> (x*y)**2 x**2*y**2
Log
Pull out power of an argument as a coefficient and split logs products into sums of logs.
Note that these only work if the arguments of the log function have the proper assumptions–the arguments must be positive and the exponents must be real–or else the
force
hint must be True:>>> from sympy import log, symbols >>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x,y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y)
Basic
This hint is intended primarily as a way for custom subclasses to enable expansion by default.
These hints are not run by default:
Complex
Split an expression into real and imaginary parts.
>>> x, y = symbols('x,y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
Note that this is just a wrapper around
as_real_imag()
. Most objects that wish to redefine_eval_expand_complex()
should consider redefiningas_real_imag()
instead.Func
Expand other functions.
>>> from sympy import gamma >>> gamma(x + 1).expand(func=True) x*gamma(x)
Trig
Do trigonometric expansions.
>>> cos(x + y).expand(trig=True) -sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x)
Note that the forms of
sin(n*x)
andcos(n*x)
in terms ofsin(x)
andcos(x)
are not unique, due to the identity \(\sin^2(x) + \cos^2(x) = 1\). The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See this MathWorld article for more information.Notes
You can shut off unwanted methods:
>>> (exp(x + y)*(x + y)).expand() x*exp(x)*exp(y) + y*exp(x)*exp(y) >>> (exp(x + y)*(x + y)).expand(power_exp=False) x*exp(x + y) + y*exp(x + y) >>> (exp(x + y)*(x + y)).expand(mul=False) (x + y)*exp(x)*exp(y)
Use deep=False to only expand on the top level:
>>> exp(x + exp(x + y)).expand() exp(x)*exp(exp(x)*exp(y)) >>> exp(x + exp(x + y)).expand(deep=False) exp(x)*exp(exp(x + y))
Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example,
mul
may distribute multiplications and preventlog
andpower_base
from expanding them. Also, ifmul
is applied beforemultinomial`, the expression might not be fully distributed. The solution is to use the various ``expand_hint
helper functions or to usehint=False
to this function to finely control which hints are applied. Here are some examples:>>> from sympy import expand, expand_mul, expand_power_base >>> x, y, z = symbols('x,y,z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z)
Here, we see that
log
was applied beforemul
. To get the mul expanded form, either of the following will work:>>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z)
A similar thing can happen with the
power_base
hint:>>> expand((x*(y + z))**x) (x*y + x*z)**x
To get the
power_base
expanded form, either of the following will work:>>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x
The parts of a rational expression can be targeted:
>>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x)
The
modulus
meta-hint can be used to reduce the coefficients of an expression post-expansion:>>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1
Either
expand()
the function or.expand()
the method can be used. Both are equivalent:>>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1
Api
Objects can define their own expand hints by defining
_eval_expand_hint()
. The function should take the form:def _eval_expand_hint(self, **hints): # Only apply the method to the top-level expression ...
See also the example below. Objects should define
_eval_expand_hint()
methods only ifhint
applies to that specific object. The generic_eval_expand_hint()
method defined in Expr will handle the no-op case.Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only.
expand()
takes care of the recursion that happens whendeep=True
.You should only call
_eval_expand_hint()
methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpectedAttributeError``s. Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by ``expand()
._eval_expand_hint()
should generally not be used at all outside of an_eval_expand_hint()
method. If you want to apply a specific expansion from within another method, use the publicexpand()
function, method, orexpand_hint()
functions.In order for expand to work, objects must be rebuildable by their args, i.e.,
obj.func(*obj.args) == obj
must hold.Expand methods are passed
**hints
so that expand hints may use ‘metahints’–hints that control how different expand methods are applied. For example, theforce=True
hint described above that causesexpand(log=True)
to ignore assumptions is such a metahint. Thedeep
meta-hint is handled exclusively byexpand()
and is not passed to_eval_expand_hint()
methods.Note that expansion hints should generally be methods that perform some kind of ‘expansion’. For hints that simply rewrite an expression, use the .rewrite() API.
Examples
>>> from sympy import Expr, sympify >>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, *, force=False, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
- sympy.core.function.count_ops(expr, visual=False)[source]¶
Return a representation (integer or expression) of the operations in expr.
- Parameters:
expr : Expr
If expr is an iterable, the sum of the op counts of the items will be returned.
visual : bool, optional
If
False
(default) then the sum of the coefficients of the visual expression will be returned. IfTrue
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.
Examples
>>> from sympy.abc import a, b, x, y >>> from sympy import sin, count_ops
Although there is not 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
- sympy.core.function.expand_mul(expr, deep=True)[source]¶
Wrapper around expand that only uses the mul hint. See the expand docstring for more information.
Examples
>>> from sympy import symbols, expand_mul, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2)
- sympy.core.function.expand_log(
- expr,
- deep=True,
- force=False,
- factor=False,
Wrapper around expand that only uses the log hint. See the expand docstring for more information.
Examples
>>> from sympy import symbols, expand_log, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) (x + y)*(log(x) + 2*log(y))*exp(x + y)
- sympy.core.function.expand_func(expr, deep=True)[source]¶
Wrapper around expand that only uses the func hint. See the expand docstring for more information.
Examples
>>> from sympy import expand_func, gamma >>> from sympy.abc import x >>> expand_func(gamma(x + 2)) x*(x + 1)*gamma(x)
- sympy.core.function.expand_trig(expr, deep=True)[source]¶
Wrapper around expand that only uses the trig hint. See the expand docstring for more information.
Examples
>>> from sympy import expand_trig, sin >>> from sympy.abc import x, y >>> expand_trig(sin(x+y)*(x+y)) (x + y)*(sin(x)*cos(y) + sin(y)*cos(x))
- sympy.core.function.expand_complex(expr, deep=True)[source]¶
Wrapper around expand that only uses the complex hint. See the expand docstring for more information.
Examples
>>> from sympy import expand_complex, exp, sqrt, I >>> from sympy.abc import z >>> expand_complex(exp(z)) I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) >>> expand_complex(sqrt(I)) sqrt(2)/2 + sqrt(2)*I/2
See also
- sympy.core.function.expand_multinomial(expr, deep=True)[source]¶
Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information.
Examples
>>> from sympy import symbols, expand_multinomial, exp >>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) x**2 + 2*x*exp(x + 1) + exp(2*x + 2)
- sympy.core.function.expand_power_exp(expr, deep=True)[source]¶
Wrapper around expand that only uses the power_exp hint.
See the expand docstring for more information.
Examples
>>> from sympy import expand_power_exp, Symbol >>> from sympy.abc import x, y >>> expand_power_exp(3**(y + 2)) 9*3**y >>> expand_power_exp(x**(y + 2)) x**(y + 2)
If
x = 0
the value of the expression depends on the value ofy
; if the expression were expanded the result would be 0. So expansion is only done ifx != 0
:>>> expand_power_exp(Symbol('x', zero=False)**(y + 2)) x**2*x**y
- sympy.core.function.expand_power_base(expr, deep=True, force=False)[source]¶
Wrapper around expand that only uses the power_base hint.
A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power’s base and exponent allow.
deep=False (default is True) will only apply to the top-level expression.
force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer.
>>> from sympy.abc import x, y, z >>> from sympy import expand_power_base, sin, cos, exp, Symbol
>>> (x*y)**2 x**2*y**2
>>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y
>>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z)
>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y
>>> expand_power_base((2*exp(y))**x) 2**x*exp(y)**x
>>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y
Notice that sums are left untouched. If this is not the desired behavior, apply full
expand()
to the expression:>>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2
>>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y**(z + 1)
The power that is unexpanded can be expanded safely when
y != 0
, otherwise different values might be obtained for the expression:>>> prev = _
If we indicate that
y
is positive but then replace it with a value of 0 after expansion, the expression becomes 0:>>> p = Symbol('p', positive=True) >>> prev.subs(y, p).expand().subs(p, 0) 0
But if
z = -1
the expression would not be zero:>>> prev.subs(y, 0).subs(z, -1) 1
See also
- sympy.core.function.nfloat(expr, n=15, exponent=False, dkeys=False)[source]¶
Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True) and those in undefined functions. When processing dictionaries, do not modify the keys unless
dkeys=True
.Examples
>>> from sympy import nfloat, cos, pi, sqrt >>> from sympy.abc import x, y >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5
Container types are not modified:
>>> type(nfloat((1, 2))) is tuple True
evalf¶
- class sympy.core.evalf.EvalfMixin[source]¶
Mixin class adding evalf capability.
- 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.
- Parameters:
subs : dict, optional
Substitute numerical values for symbols, e.g.
subs={x:3, y:1+pi}
. The substitutions must be given as a dictionary.maxn : int, optional
Allow a maximum temporary working precision of maxn digits.
chop : bool or number, optional
Specifies how to replace tiny real or imaginary parts in subresults by exact zeros.
When
True
the chop value defaults to standard precision.Otherwise the chop value is used to determine the magnitude of “small” for purposes of chopping.
>>> from sympy import N >>> x = 1e-4 >>> N(x, chop=True) 0.000100000000000000 >>> N(x, chop=1e-5) 0.000100000000000000 >>> N(x, chop=1e-4) 0
strict : bool, optional
Raise
PrecisionExhausted
if any subresult fails to evaluate to full accuracy, given the available maxprec.quad : str, optional
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try
quad='osc'
.verbose : bool, optional
Print debug information.
Notes
When Floats are naively substituted into an expression, precision errors may adversely affect the result. For example, adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is then subtracted, the result will be 0. That is exactly what happens in the following:
>>> from sympy.abc import x, y, z >>> values = {x: 1e16, y: 1, z: 1e16} >>> (x + y - z).subs(values) 0
Using the subs argument for evalf is the accurate way to evaluate such an expression:
>>> (x + y - z).evalf(subs=values) 1.00000000000000
- 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.
- Parameters:
subs : dict, optional
Substitute numerical values for symbols, e.g.
subs={x:3, y:1+pi}
. The substitutions must be given as a dictionary.maxn : int, optional
Allow a maximum temporary working precision of maxn digits.
chop : bool or number, optional
Specifies how to replace tiny real or imaginary parts in subresults by exact zeros.
When
True
the chop value defaults to standard precision.Otherwise the chop value is used to determine the magnitude of “small” for purposes of chopping.
>>> from sympy import N >>> x = 1e-4 >>> N(x, chop=True) 0.000100000000000000 >>> N(x, chop=1e-5) 0.000100000000000000 >>> N(x, chop=1e-4) 0
strict : bool, optional
Raise
PrecisionExhausted
if any subresult fails to evaluate to full accuracy, given the available maxprec.quad : str, optional
Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try
quad='osc'
.verbose : bool, optional
Print debug information.
Notes
When Floats are naively substituted into an expression, precision errors may adversely affect the result. For example, adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is then subtracted, the result will be 0. That is exactly what happens in the following:
>>> from sympy.abc import x, y, z >>> values = {x: 1e16, y: 1, z: 1e16} >>> (x + y - z).subs(values) 0
Using the subs argument for evalf is the accurate way to evaluate such an expression:
>>> (x + y - z).evalf(subs=values) 1.00000000000000
- sympy.core.evalf.N(x, n=15, **options)[source]¶
Calls x.evalf(n, **options).
Explanations
Both .n() and N() are equivalent to .evalf(); use the one that you like better. See also the docstring of .evalf() for information on the options.
Examples
>>> from sympy import Sum, oo, N >>> from sympy.abc import k >>> Sum(1/k**k, (k, 1, oo)) Sum(k**(-k), (k, 1, oo)) >>> N(_, 4) 1.291
containers¶
- class sympy.core.containers.Tuple(*args, **kwargs)[source]¶
Wrapper around the builtin tuple object.
- Parameters:
sympify : bool
If
False
,sympify
is not called onargs
. This can be used for speedups for very large tuples where the elements are known to already be SymPy objects.
Explanation
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.
Examples
>>> from sympy import Tuple, symbols >>> 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)
- property kind¶
The kind of a Tuple instance.
The kind of a Tuple is always of
TupleKind
but parametrised by the number of elements and the kind of each element.Examples
>>> from sympy import Tuple, Matrix >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(Matrix([1, 2]), 1).kind TupleKind(MatrixKind(NumberKind), NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind)
- class sympy.core.containers.TupleKind(*args)[source]¶
TupleKind is a subclass of Kind, which is used to define Kind of
Tuple
.Parameters of TupleKind will be kinds of all the arguments in Tuples, for example
- Parameters:
args : tuple(element_kind)
element_kind is kind of element. args is tuple of kinds of element
Examples
>>> from sympy import Tuple >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind)
- class sympy.core.containers.Dict(*args)[source]¶
Wrapper around the builtin dict object.
Explanation
The Dict is a subclass of Basic, so that it works well in the SymPy framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be changed afterwards. Otherwise it behaves identically to the Python dict.
Examples
>>> from sympy import Dict, Symbol
>>> D = Dict({1: 'one', 2: 'two'}) >>> for key in D: ... if key == 1: ... print('%s %s' % (key, D[key])) 1 one
The args are sympified so the 1 and 2 are Integers and the values are Symbols. Queries automatically sympify args so the following work:
>>> 1 in D True >>> D.has(Symbol('one')) # searches keys and values True >>> 'one' in D # not in the keys False >>> D[1] one
exprtools¶
- sympy.core.exprtools.gcd_terms(
- terms,
- isprimitive=False,
- clear=True,
- fraction=True,
Compute the GCD of
terms
and put them together.- Parameters:
terms : Expr
Can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum.
isprimitive : bool, optional
If
isprimitive
is True the _gcd_terms will not run the primitive method on the terms.clear : bool, optional
It controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1.
fraction : bool, optional
When True (default), will put the expression over a common denominator.
Examples
>>> from sympy import gcd_terms >>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False) (x**2/2 + 1)/(x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False) (x/2 + 1/x)/y
The
clear
flag was ignored in this case because the returned expression was a rational expression, not a simple sum.See also
- sympy.core.exprtools.factor_terms(
- expr: Expr | complex,
- radical=False,
- clear=False,
- fraction=False,
- sign=True,
Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed.
- Parameters:
radical: bool, optional
If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr.
clear : bool, optional
If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients.
fraction : bool, optional
If fraction=True (default is False) then a common denominator will be constructed for the expression.
sign : bool, optional
If sign=True (default) then even if the only factor in common is a -1, it will be factored out of the expression.
Examples
>>> from sympy import factor_terms, Symbol >>> from sympy.abc import x, y >>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A)
When
clear
is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions:>>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2
If a -1 is all that can be factored out, to not factor it out, the flag
sign
must be False:>>> factor_terms(-x - y) -(x + y) >>> factor_terms(-x - y, sign=False) -x - y >>> factor_terms(-2*x - 2*y, sign=False) -2*(x + y)
See also
kind¶
- class sympy.core.kind.Kind(*args)[source]¶
Base class for kinds.
Kind of the object represents the mathematical classification that the entity falls into. It is expected that functions and classes recognize and filter the argument by its kind.
Kind of every object must be carefully selected so that it shows the intention of design. Expressions may have different kind according to the kind of its arguments. For example, arguments of
Add
must have common kind since addition is group operator, and the resultingAdd()
has the same kind.For the performance, each kind is as broad as possible and is not based on set theory. For example,
NumberKind
includes not only complex number but expression containingS.Infinity
orS.NaN
which are not strictly number.Kind may have arguments as parameter. For example,
MatrixKind()
may be constructed with one element which represents the kind of its elements.Kind
behaves in singleton-like fashion. Same signature will return the same object.
- sympy.core.kind.NumberKind¶
alias of NumberKind
- sympy.core.kind.UndefinedKind¶
alias of UndefinedKind
- sympy.core.kind.BooleanKind¶
alias of BooleanKind
Sorting¶
- sympy.core.sorting.default_sort_key(item, order=None)[source]¶
Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
item
is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key.The
order
argument is passed along to the sort_key routine and is used to determine how the terms within an expression are ordered. (See examples below)order
options are: ‘lex’, ‘grlex’, ‘grevlex’, and reversed values of the same (e.g. ‘rev-lex’). The default order value is None (which translates to ‘lex’).Examples
>>> from sympy import S, I, default_sort_key, sin, cos, sqrt >>> from sympy.core.function import UndefinedFunction >>> from sympy.abc import x
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x) True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f')) ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key('1') ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key(S.One) ((1, 0, 'Number'), (0, ()), (), 1) >>> default_sort_key(2) ((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for SymPy objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 does not have a sort_key method; that’s why default_sort_key is used. Note, that it also handles sympification of non-string items likes ints:
>>> a = [2, I, -I] >>> sorted(a, key=default_sort_key) [2, -I, I]
The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc…:
>>> a.sort(key=default_sort_key); a[0] 2 >>> min(a, key=default_sort_key) 2
Notes
The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions:
>>> a, b = x, 1/x
Since
a
has only 1 term, its value of sort_key is unaffected byorder
:>>> a.sort_key() == a.sort_key('rev-lex') True
If
a
andb
are combined then the key will differ because there are terms that can be ordered:>>> eq = a + b >>> eq.sort_key() == eq.sort_key('rev-lex') False >>> eq.as_ordered_terms() [x, 1/x] >>> eq.as_ordered_terms('rev-lex') [1/x, x]
But since the keys for each of these terms are independent of
order
’s value, they do not sort differently when they appear separately in a list:>>> sorted(eq.args, key=default_sort_key) [1/x, x] >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex')) [1/x, x]
The order of terms obtained when using these keys is the order that would be obtained if those terms were factors in a product.
Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others:
>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key) [sin(x)*cos(x), sin(x)] >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key) [sqrt(x), x, x**2, x**3]
- sympy.core.sorting.ordered(seq, keys=None, default=True, warn=False)[source]¶
Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed.
Two default keys will be applied if 1) keys are not provided or 2) the given keys do not resolve all ties (but only if
default
is True). The two keys are_nodes
(which places smaller expressions before large) anddefault_sort_key
which (if thesort_key
for an object is defined properly) should resolve any ties. This strategy is similar to sorting done byBasic.compare
, but differs in thatordered
never makes a decision based on an objects name.If
warn
is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical.Examples
>>> from sympy import ordered, count_ops >>> from sympy.abc import x, y
The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable):
>>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3]
The default_sort_key allows the tie to be broken:
>>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3]
Here, sequences are sorted by length, then sum:
>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
If
warn
is True, an error will be raised if there were not enough keys to break ties:>>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties
Notes
The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible.
This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key, then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed.
Random¶
When you need to use random numbers in SymPy library code, import from here
so there is only one generator working for SymPy. Imports from here should
behave the same as if they were being imported from Python’s random module.
But only the routines currently used in SymPy are included here. To use others
import rng
and access the method directly. For example, to capture the
current state of the generator use rng.getstate()
.
There is intentionally no Random to import from here. If you want
to control the state of the generator, import seed
and call it
with or without an argument to set the state.
Examples¶
>>> from sympy.core.random import random, seed
>>> assert random() < 1
>>> seed(1); a = random()
>>> b = random()
>>> seed(1); c = random()
>>> assert a == c
>>> assert a != b # remote possibility this will fail
- sympy.core.random.random_complex_number(
- a=2,
- b=-1,
- c=3,
- d=1,
- rational=False,
- tolerance=None,
Return a random complex number.
To reduce chance of hitting branch cuts or anything, we guarantee b <= Im z <= d, a <= Re z <= c
When rational is True, a rational approximation to a random number is obtained within specified tolerance, if any.
- sympy.core.random.verify_numerically(
- f,
- g,
- z=None,
- tol=1e-06,
- a=2,
- b=-1,
- c=3,
- d=1,
Test numerically that f and g agree when evaluated in the argument z.
If z is None, all symbols will be tested. This routine does not test whether there are Floats present with precision higher than 15 digits so if there are, your results may not be what you expect due to round- off errors.
Examples
>>> from sympy import sin, cos >>> from sympy.abc import x >>> from sympy.core.random import verify_numerically as tn >>> tn(sin(x)**2 + cos(x)**2, 1, x) True
- sympy.core.random.test_derivative_numerically(
- f,
- z,
- tol=1e-06,
- a=2,
- b=-1,
- c=3,
- d=1,
Test numerically that the symbolically computed derivative of f with respect to z is correct.
This routine does not test whether there are Floats present with precision higher than 15 digits so if there are, your results may not be what you expect due to round-off errors.
Examples
>>> from sympy import sin >>> from sympy.abc import x >>> from sympy.core.random import test_derivative_numerically as td >>> td(sin(x), x) True
- sympy.core.random._randrange(seed=None)[source]¶
Return a randrange generator.
seed
can beNone - return randomly seeded generator
int - return a generator seeded with the int
list - the values to be returned will be taken from the list in the order given; the provided list is not modified.
Examples
>>> from sympy.core.random import _randrange >>> rr = _randrange() >>> rr(1000) 999 >>> rr = _randrange(3) >>> rr(1000) 238 >>> rr = _randrange([0, 5, 1, 3, 4]) >>> rr(3), rr(3) (0, 1)
- sympy.core.random._randint(seed=None)[source]¶
Return a randint generator.
seed
can beNone - return randomly seeded generator
int - return a generator seeded with the int
list - the values to be returned will be taken from the list in the order given; the provided list is not modified.
Examples
>>> from sympy.core.random import _randint >>> ri = _randint() >>> ri(1, 1000) 999 >>> ri = _randint(3) >>> ri(1, 1000) 238 >>> ri = _randint([0, 5, 1, 2, 4]) >>> ri(1, 3), ri(1, 3) (1, 2)
Traversal¶
- sympy.core.traversal.bottom_up(rv, F, atoms=False, nonbasic=False)[source]¶
Apply
F
to all expressions in an expression tree from the bottom up. Ifatoms
is True, applyF
even if there are no args; ifnonbasic
is True, try to applyF
to non-Basic objects.
- sympy.core.traversal.postorder_traversal(node, keys=None)[source]¶
Do a postorder traversal of a tree.
This generator recursively yields nodes that it has visited in a postorder fashion. That is, it descends through the tree depth-first to yield all of a node’s children’s postorder traversal before yielding the node itself.
- Parameters:
node : SymPy expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if
key
is simply True then the default keys ofordered
will be used (node count and default_sort_key).- Yields:
subtree : SymPy expression
All of the subtrees in the tree.
Examples
>>> from sympy import postorder_traversal >>> from sympy.abc import w, x, y, z
The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique.
>>> list(postorder_traversal(w + (x + y)*z)) [z, y, x, x + y, z*(x + y), w, w + z*(x + y)] >>> list(postorder_traversal(w + (x + y)*z, keys=True)) [w, z, x, y, x + y, z*(x + y), w + z*(x + y)]
- sympy.core.traversal.preorder_traversal(node, keys=None)[source]¶
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a pre-order fashion. That is, it yields the current node then descends through the tree breadth-first to yield all of a node’s children’s pre-order traversal.
For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary.
- Parameters:
node : SymPy expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic objects are processed in arbitrary order. If key is defined, it will be passed along to ordered() as the only key(s) to use to sort the arguments; if
key
is simply True then the default keys of ordered will be used.- Yields:
subtree : SymPy expression
All of the subtrees in the tree.
Examples
>>> from sympy import preorder_traversal, symbols >>> x, y, z = symbols('x y z')
The nodes are returned in the order that they are encountered unless key is given; simply passing key=True will guarantee that the traversal is unique.
>>> list(preorder_traversal((x + y)*z, keys=None)) [z*(x + y), z, x + y, y, x] >>> list(preorder_traversal((x + y)*z, keys=True)) [z*(x + y), z, x + y, x, y]
- sympy.core.traversal.use(expr, func, level=0, args=(), kwargs={})[source]¶
Use
func
to transformexpr
at the given level.Examples
>>> from sympy import use, expand >>> from sympy.abc import x, y
>>> f = (x + y)**2*x + 1
>>> use(f, expand, level=2) x*(x**2 + 2*x*y + y**2) + 1 >>> expand(f) x**3 + 2*x**2*y + x*y**2 + 1
- sympy.core.traversal.walk(e, *target)[source]¶
Iterate through the args that are the given types (target) and return a list of the args that were traversed; arguments that are not of the specified types are not traversed.
Examples
>>> from sympy.core.traversal import walk >>> from sympy import Min, Max >>> from sympy.abc import x, y, z >>> list(walk(Min(x, Max(y, Min(1, z))), Min)) [Min(x, Max(y, Min(1, z)))] >>> list(walk(Min(x, Max(y, Min(1, z))), Min, Max)) [Min(x, Max(y, Min(1, z))), Max(y, Min(1, z)), Min(1, z)]
See also