Navigation

SymPy runs under the Python Programming Language, so there are some things that may behave
differently than they do in other, independent computer algebra systems
like Maple or Mathematica. These are some of the gotchas and pitfalls
that you may encounter when using SymPy. See also the FAQ, the Tutorial, the
remainder of the SymPy Docs, and the official Python Tutorial.

The equals sign (=) is the assignment operator, not an equality. If
you want to do , use Eq(x,y) for equality.
Alternatively, all expressions are assumed to equal zero, so you can
just subtract one side and use x-y.

The proper use of the equals sign is to assign expressions to variables.

Double equals signs (==) are used to test equality. However, this
tests expressions exactly, not symbolically. For example:

>>> (x+1)**2==x**2+2*x+1False>>> (x+1)**2==(x+1)**2True

If you want to test for symbolic equality, one way is to subtract one
expression from the other and run it through functions like
expand(), simplify(), and trigsimp() and see if the
equation reduces to 0.

When you use = to do assignment, remember that in Python, as in most
programming languages, the variable does not change if you change the
value you assigned to it. The equations you are typing use the values
present at the time of creation to “fill in” values, just like regular
Python definitions. They are not altered by changes made afterwards.
Consider the following:

>>> fromsympyimportSymbol>>> a=Symbol('a')# Create a Symbol named a, that is also stored in the variable "a">>> b=a+1# Create another object, b, that refers to 'a'>>> printb1 + a>>> a=4# a now points to the literal integer 4, not Symbol('a')>>> printa4>>> b# But b is still pointing at Symbol('a')1 + a

Changing quantity a does not change b; you are not working
with a set of simultaneous equations. It might be helpful to remember
that the string that gets printed when you print a variable referring to
a sympy object is the string that was given to it when it was created;
that string does not have to be the same as the variable that you assign
it to.

>>> fromsympyimportvar>>> r,t,d=var('rate time short_life')>>> d=r*t>>> printdrate*time>>> r=80>>> t=2>>> printd# We haven't changed d, only r and trate*time>>> d=r*t>>> printd# Now d is using the current values of r and t160

If you need variables that have dependence on each other, you can define
functions. Use the def operator. Indent the body of the function.
See the Python docs for more information on defining functions.

Symbols are variables, and like all other variables, they need to be
assigned before you can use them. For example:

>>> importsympy>>> z**2# z is not defined yet Traceback (most recent call last):
File "<stdin>", line 1, in <module>NameError: name 'z' is not defined>>> sympy.var('z')# This is the easiest way to define z as a standard symbolz>>> z**2z**2

If you use isympy, it runs the following commands for you,
giving you some default Symbols and Functions.

If you want control over the assumptions of the variables, use
Symbol() and symbols(). See Keyword
Arguments<keyword-arguments> below.

Lastly, it is recommended that you not use I, E, S,
N, C, O, or Q for variable or symbol names, as those
are used for the imaginary unit (), the base of the natural
logarithm (), the sympify() function (see Symbolic
Expressions<symbolic-expressions> below), numeric evaluation (N()
is equivalent to evalf() ), the class registry (for
things like C.cos(), to prevent cyclic imports in some code),
the big O order symbol
(as in ), and the assumptions object that holds a list of supported ask keys (such as Q.real), respectively. You can use the mnemonic
QCOSINE to remember what Symbols are defined by default in SymPy. Or
better yet, always use lowercase letters for Symbol names. Python will
not prevent you from overriding default SymPy names or functions, so be
careful.

>>> fromsympyimport*>>> cos(pi)# cos and pi are a built-in sympy names.-1>>> pi=3# Notice that there is no warning for overriding pi.>>> cos(pi)cos(3)>>> defcos(x):# No warning for overriding built-in functions either.... return5*x...>>> cos(pi)15

To get a full list of all default names in SymPy do:

>>> importsympy>>> dir(sympy)# A big list of all default sympy names and functions follows.# Ignore everything that starts and ends with __.

If you have iPython installed and
use isympy, you can also press the TAB key to get a list of
all built-in names and to autocomplete. Also, see this page for a
trick for getting tab completion in the regular Python console.

SymPy uses its own classes for integers, rational numbers, and floating
point numbers instead of the default Python int and float
types because it allows for more control. But you have to be careful.
If you type an expression that just has numbers in it, it will default
to a Python expression. Use the sympify() function, or just
S(), to ensure that something is a SymPy expression.

If you include numbers in a sympy expression, they will be sympified
automatically, but there is one gotcha you should be aware of. If you
do <number>/<number> inside of a SymPy expression, Python will
evaluate the two numbers into a float before SymPy has a chance to get
to them. The solution is to sympify() one of the numbers, or use
Rational.

Note

A common mistake is copying an expression that is printed and
reusing it. If the expression has a Rational (i.e.,
<number>/<number>) in it, you will not get the same result.

>>> x=Symbol('x')>>> printsolve(x**2-2,x)[-2**(1/2), 2**(1/2)]>>> [-2**(1/2),2**(1/2)]# If we just copy and paste, the expression is evaluated by Python [-1.41421356237, 1.41421356237]>>> # One solution is to just assign the expression to a variable>>> # if we need to use it again.>>> a=solve(x**2-2,x)>>> a[-2**(1/2), 2**(1/2)]>>> # The other solution is to put quotes around the expression and run it through S() (sympify)>>> S("[-2**(1/2), 2**(1/2)]")[-2**(1/2), 2**(1/2)]

Also, if you do not use isympy, you should do from__future__importdivision to prevent the / sign from performing
integer division.

>>> 1/2# in regular python, this defaults to integer division, which truncates the fractional part 0>>> from__future__importdivision>>> fromsympyimport*>>> 1/2# This uses regular division, but it still evaluates to a python float 0.5>>> 1//2# You can still achieve integer division with //0>>> # Either of these will produce the rational number one half:>>> S(1)/21/2>>> Rational(1,2)1/2>>> var('x')x>>> x**(1/2)# Be careful with <number>/<number>, even in SymPy expressions x**0.5>>> x**(S(1)/2)x**(1/2)>>> sqrt(x)# sqrt(x) does the exact same thing as x**(S(1)/2)x**(1/2)>>> sqrt(x)==x**(S(1)/2)True

Rational only works for number/number and is only meant for
rational numbers. If you want a fraction with symbols or expressions in
it, just use /. If you do number/expression or expression/number,
then the number will automatically be converted in to a SymPy Number.
You only need to be careful with number/number.

SymPy uses the same default operators as Python. Most of these, like
*/+-, are standard. Aside from integer division discussed in
Python numbers vs. SymPy Numbers above,
you should also be aware that implied multiplication is not allowed. You
need to use * whenever you wish to multiply something. Also, to
raise something to a power, use **, not ^ as many computer
algebra systems use. Parentheses () change operator precedence as
you would normally expect.

SymPy uses different names for some functions than most computer algebra
systems. In particular, the inverse trig functions use the python names
of asin(), acos() and so on instead of the usual arcsin
and arccos. Use the methods described in Symbols
above to see the names of all SymPy functions.

Square brackets [] denote a list. A list is a container that holds
any number of different objects. A list can contain anything, including
items of different types. Lists are mutable, which means that you can
change the elements of a list after it has been created. You access the
items of a list also using square brackets, placing them after the list
or list variable. Items are numbered using the space before the item.

Note

List indexes begin at 0.

Example:

>>> a=[x,1]# A simple list of two items>>> a[x, 1]>>> a[0]# This is the first itemx>>> a[0]=2# You can change values of lists after they have been created>>> printa[2, 1]>>> printsolve(x**2+2*x-1,x)# Some functions return lists[-1 + 2**(1/2), -1 - 2**(1/2)]

Note

See the Python docs for more information on lists and the square
bracket notation for accessing elements of a list.

Curly brackets {} denote a dictionary, or a dict for short. A
dictionary is an unordered list of non-duplicate keys and values. The
syntax is {key:value}. You can access values of keys using square
bracket notation.

Parentheses (), aside from changing operator precedence and their
use in function calls, (like cos(x)), are also used for tuples. A
tuple is identical to a list, except that it is not
mutable. That means that you can not change their values after they
have been created. In general, you will not need tuples in SymPy, but
sometimes it can be more convenient to type parentheses instead of
square brackets.

>>> t=(1,2,x)# Tuples are like lists>>> t(1, 2, x)>>> t[0]1>>> t[0]=4# Except you can not change them after they have been createdTraceback (most recent call last):
File "<console>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>> (x,)# Single element tuples, unlike lists, must have a comma in them.(x,)>>> (x)# Not a tuplex>>> # integrate takes a tuple as the second argument if you want to integrate with limits.>>> integrate(x**2,(x,0,1))1/3>>> integrate(x**2,[x,0,1])# But a list works too.1/3

Aside from the usage described above, equals signs
(=) are also used to give named arguments to functions. Any
function that has key=value in its parameters list (see below on how
to find this out), then key is set to value by default. You can
change the value of the key by supplying your own value using the equals
sign in the function call. Also, functions that have ** followed by
a name in the parameters list (usually **kwargs or
**assumptions) allow you to add any number of key=value pairs
that you want, and they will all be evaluated according to the function.

Although all docs are available at docs.sympy.org or on the SymPy Wiki, you can also get info on functions from within the Python interpreter that runs SymPy. The easiest way to do this is to do help(function), or function? if you are using ipython:

In [1]: help(powsimp) # help() works everywhere
In [2]: # But in ipython, you can also use ?, which is better because it
In [3]: # it gives you more information
In [4]: powsimp?

These will give you the function parameters and docstring for
powsimp(). The output will look something like this:

powsimp(expr, deep) -> reduces expression by combining powers with
similar bases and exponents.

== Notes ==

If deep is True then powsimp() will also simplify arguments of
functions. By default deep is set to False.
You can make powsimp() only combine bases or only combine exponents by
changing combine=’base’ or combine=’exp’. By default, combine=’all’,
which does both. combine=’base’ will only combine:

a a a 2x x
x * y => (x*y) as well as things like 2 => 4

and combine=’exp’ will only combine

a b (a + b)
x * x => x

combine=’exp’ will strictly only combine exponents in the way that used
to be automatic. Also use deep=True if you need the old behavior.

When combine=’all’, ‘exp’ is evaluated first. Consider the first
example below for when there could be an ambiguity relating to this.
This is done so things like the second example can be completely
combined. If you want ‘base’ combined first, do something like
powsimp(powsimp(expr, combine=’base’), combine=’exp’).

Another useful option is the source() function. This will print
the source code of a function, including any docstring that it may have.
You can also do function?? in ipython. For example,
from SymPy 0.6.5:

>>> source(simplify)# simplify() is actually only 2 lines of code. In file: ./sympy/simplify/simplify.pydef simplify(expr): """Naively simplifies the given expression. ... Simplification is not a well defined term and the exact strategies this function tries can change in the future versions of SymPy. If your algorithm relies on "simplification" (whatever it is), try to determine what you need exactly - is it powsimp()? radsimp()? together()?, logcombine()?, or something else? And use this particular function directly, because those are well defined and thus your algorithm will be robust. ... """ expr = Poly.cancel(powsimp(expr)) return powsimp(together(expr.expand()), combine='exp', deep=True)