Sympy Tutorial
Sympy Tutorial
i
SymPy
Audience
This tutorial is designed for python programmers who would like to get introduced to the
symbolic mathematics including basics of symbolic computing, basic symbolic operations,
calculus, matrices and some select advanced topics.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of python
programming language. This tutorial assumes a decent mathematical background. Most
examples require knowledge lower than a calculus level, and some require knowledge at
a calculus level.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
ii
SymPy
Table of Contents
About the Tutorial ........................................................................................................................................... ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
6. SymPy ― Substitution............................................................................................................................. 11
Or function .................................................................................................................................................... 17
ITE function.................................................................................................................................................... 19
iii
SymPy
simplify .......................................................................................................................................................... 22
expand ........................................................................................................................................................... 22
factor ............................................................................................................................................................. 23
collect ............................................................................................................................................................ 23
cancel............................................................................................................................................................. 24
trigsimp .......................................................................................................................................................... 24
powersimp ..................................................................................................................................................... 25
combsimp ...................................................................................................................................................... 25
logcombine .................................................................................................................................................... 26
binomial ......................................................................................................................................................... 41
add() .............................................................................................................................................................. 44
mul() .............................................................................................................................................................. 45
inverse() ......................................................................................................................................................... 45
iv
SymPy
pow() ............................................................................................................................................................. 45
exp() ............................................................................................................................................................... 46
Linear equation.............................................................................................................................................. 48
differential equation...................................................................................................................................... 48
Point .............................................................................................................................................................. 57
Line ................................................................................................................................................................ 57
Triangle .......................................................................................................................................................... 58
Ellipse............................................................................................................................................................. 58
v
1. SymPy ― Introduction SymPy
SymPy has a wide range of features applicable in the field of basic symbolic arithmetic,
calculus, algebra, discrete mathematics, quantum physics, etc. SymPy is capable of
formatting the results in variety of formats including LaTeX, MathML, etc. SymPy is
distributed under New BSD License. A team of developers led by Ondřej Čertík and Aaron
Meurer published first version of SymPy in 2007. Its current version is 1.5.1.
Polynomials
Calculus
Discrete maths
Matrices
Geometry
Plotting
Physics
Statistics
Combinatorics
1
2. SymPy ― Installation SymPy
SymPy has one important prerequisite library named mpmath. It is a Python library for
real and complex floating-point arithmetic with arbitrary precision. However, Python's
package installer PIP installs it automatically when SymPy is installed as follows:
Other Python distributions such as Anaconda, Enthought Canopy, etc., may have SymPy
already bundled in it. To verify, you can type the following in the Python prompt:
And you get the below output as the current version of sympy:
'1.5.1'
2
3. SymPy ― Symbolic Computation SymPy
5.0 2.6457513110645907
As you can see, square root of 7 is calculated approximately. But in SymPy square roots
of numbers that are not perfect squares are left unevaluated by default as given below:
sqrt(7)
It is possible to simplify and show result of expression symbolically with the code snippet
below:
3.4641016151377544
You need to use the below code snippet to execute the same using sympy:
##sympy output
>>> print (sympy.sqrt(12))
2*sqrt(3)
SymPy code, when run in Jupyter notebook, makes use of MathJax library to render
mathematical symbols in LatEx form. It is shown in the below code snippet:
3
SymPy
On executing the above command in python shell, following output will be generated:
Integral(x**x, x)
Which is equivalent to
∫ 𝒙𝒙 𝒅𝒙
The square root of a non-perfect square can be represented by Latex as follows using
traditional symbol:
√𝟕
A symbolic computation system such as SymPy does all sorts of computations (such as
derivatives, integrals, and limits, solve equations, work with matrices) symbolically.
SymPy package has different modules that support plotting, printing (like LATEX), physics,
statistics, combinatorics, number theory, geometry, logic, etc.
4
4. SymPy ― Numbers SymPy
The core module in SymPy package contains Number class which represents atomic
numbers. This class has two subclasses: Float and Rational class. Rational class is further
extended by Integer class.
𝟔. 𝟑𝟐
SymPy can convert an integer or a string to float.
>>> Float(10)
𝟏𝟎. 𝟎
Float('1.33E5')# scientific notation
𝟏𝟑𝟑𝟎𝟎𝟎. 𝟎
While converting to float, it is also possible to specify number of digits for precision as
given below:
>>> Float(1.33333,2)
𝟏. 𝟑
A representation of a number (p/q) is represented as object of Rational class with q being
a non-zero number.
>>> Rational(3/4)
𝟑
𝟒
If a floating point number is passed to Rational() constructor, it returns underlying value
of its binary representation
>>> Rational(0.2)
𝟑𝟔𝟎𝟐𝟖𝟕𝟗𝟕𝟎𝟏𝟖𝟗𝟔𝟑𝟗𝟕
𝟏𝟖𝟎𝟏𝟒𝟑𝟗𝟖𝟓𝟎𝟗𝟒𝟖𝟏𝟗𝟖𝟒
>>> Rational(0.2).limit_denominator(100)
𝟏
𝟓
When a string is passed to Rational() constructor, a rational number of arbitrary precision
is returned.
>>> Rational("3.65")
𝟕𝟑
𝟐𝟎
Rational object can also be obtained if two number arguments are passed. Numerator and
denominator parts are available as properties.
>>> a=Rational(3,5)
>>> print (a)
>>> print ("numerator:{}, denominator:{}".format(a.p, a.q))
3/5
numerator:3, denominator:5
>>> a
𝟑
𝟓
Integer class in SymPy represents an integer number of any size. The constructor can
accept a Float or Rational number, but the fractional part is discarded
>>> Integer(10)
𝟏𝟎
6
SymPy
>>> Integer(3.4)
>>> Integer(2/7)
𝟎
SymPy has a RealNumber class that acts as alias for Float. SymPy also defines Zero and
One as singleton classes accessible with S.Zero and S.One respectively as shown below:
>>> S.Zero
>>> S.One
𝟏
Other predefined Singleton number objects are Half, NaN, Infinity and ImaginaryUnit
nan
Infinity is available as oo symbol object or S.Infinity
>>> S.Infinity
7
SymPy
∞
ImaginaryUnit number can be imported as I symbol or accessed as S.ImaginaryUnit and
represents square root of -1
When you execute the above code snippet, you get the following output:
>>> S.ImaginaryUnit
When you execute the above code snippet, you get the following output:
−𝟏
8
5. SymPy ― Symbols SymPy
Symbol is the most important class in symPy library. As mentioned earlier, symbolic
computations are done with symbols. SymPy variables are objects of Symbols class.
The above code snippet gives an output equivalent to the below expression:
𝒙𝟐 + 𝒚𝟐
A symbol may be of more than one alphabets.
>>> s=Symbol('side')
>>> s**3
The above code snippet gives an output equivalent to the below expression:
𝒔𝒊𝒅𝒆𝟑
SymPy also has a Symbols() function that can define multiple symbols at once. String
contains names of variables separated by comma or space.
In SymPy's abc module, all Latin and Greek alphabets are defined as symbols. Hence,
instead of instantiating Symbol object, this method is convenient.
However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with
more than one alphabets are not defined in abc module, for which you should use Symbol
object as above. The abc module defines special names that can detect definitions in
default SymPy namespace. clash1 contains single letters and clash2 has multi letter
clashing symbols
>>> _clash2
>>> symbols('mark(1:4)')
10
6. SymPy ― Substitution SymPy
The above code snippet gives an output equivalent to the below expression:
>>> expr.subs(x,a)
The above code snippet gives an output equivalent to the below expression:
>>> expr=a*a+2*a+5
>>> expr
The above code snippet gives an output equivalent to the below expression:
𝒂𝟐 + 𝟐𝒂 + 𝟓
expr.subs(a,5)
𝟒𝟎
𝟎
This function is also used to replace a subexpression with another subexpression. In
following example, b is replaced by a+b.
11
SymPy
The above code snippet gives an output equivalent to the below expression:
(𝟐𝒂 + 𝒃)𝟐
12
7. SymPy ― sympify() function SymPy
The sympify() function is used to convert any arbitrary expression such that it can be used
as a SymPy expression. Normal Python objects such as integer objects are converted in
SymPy. Integer, etc.., strings are also converted to SymPy expressions.
>>> expr="x**2+3*x+2"
>>> expr1=sympify(expr)
>>> expr1
>>> expr1.subs(x,2)
𝟏𝟐
Any Python object can be converted in SymPy object. However, since the conversion
internally uses eval() function, unsanitized expression should not be used, else
SympifyError is raised.
>>> sympify("x***2")
---------------------------------------------------------------------------
SympifyError: Sympify of expression 'could not parse 'x***2'' failed, because of exception
being raised.
The sympify() function takes following arguments: * strict: default is False. If set to True,
only the types for which an explicit conversion has been defined are converted. Otherwise,
SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be
converted into their SymPy equivalents without evaluating expression.
>>> sympify("10/5+4/2")
𝟏𝟎 𝟒
+
𝟓 𝟐
13
8. SymPy ― evalf() function SymPy
This function evaluates a given numerical expression upto a given floating point precision
upto 100 digits. The function also takes subs parameter a dictionary object of numerical
values for symbols. Consider following expression
The above code snippet gives an output equivalent to the below expression:
𝝅𝒓𝟐
To evaluate above expression using evalf() function by substituting r with 5
>>> expr.evalf(subs={r:5})
𝟕𝟖. 𝟓𝟑𝟗𝟖𝟏𝟔𝟑𝟑𝟗𝟕𝟒𝟒𝟖
By default, floating point precision is upto 15 digits which can be overridden by any number
upto 100. Following expression is evaluated upto 20 digits of precision.
>>> expr=a/b
>>> expr.evalf(20, subs={a:100, b:3})
𝟑𝟑. 𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑𝟑
14
9. SymPy - Lambdify() function SymPy
The lambdify function translates SymPy expressions into Python functions. If an expression
is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify
acts like a lambda function, except it converts the SymPy names to the names of the given
numerical library, usually NumPy. By default, lambdify on implementations in the math
standard library.
>>> expr=1/sin(x)
>>> f=lambdify(x, expr)
>>> f(3.14)
627.8831939138764
The expression might have more than one variables. In that case, first argument to
lambdify() function is a list of variables, followed by the expression to be evaluated.
>>> expr=a**2+b**2
>>> f=lambdify([a,b],expr)
>>> f(2,3)
13
However, to leverage numpy library as numerical backend, we have to define the same as
an argument for lambdify() function.
We use two numpy arrays for two arguments a and b in the above function. The execution
time is considerably fast in case of numpy arrays.
15
10. SymPy ― Logical Expressions SymPy
BooleanTrue function
This function is equivalent of True as in core Python. It returns a singleton that can be
retrieved by S.true.
(True, True)
BooleanFalse function
Similarly, this function is equivalent to Boolean False in Python and can be accessed by
S.false
(False, False)
And function
A logical AND function evaluates its two arguments and returns False if either of them is
False. The function emulates & operator.
(True, True)
16
SymPy
>>> y=False
>>> And(x,y), x&y
(False, False)
Or function
This function evaluates two Boolean arguments and returns True if either of them is True.
The | operator conveniently emulates its behaviour.
(True, True)
>>> x=False
>>> y=False
>>> Or(x,y), x|y
(False, False)
Not Function
A Logical Not function results in negation of the Boolean argument. It returns True if its
argument is False and returns False if True. The ~ operator performs the operation similar
to Not function. It is shown in the example below:
(False, True)
17
SymPy
(True, False)
Xor Function
The Logical XOR (exclusive OR) function returns True if an odd number of the arguments
are True and the rest are False and returns False if an even number of the arguments are
True and the rest are False. Similar operation is performed by ^ operator.
(True, True)
True
In above case, three (odd number) arguments are True, hence Xor returns true. However,
if number of True arguments is even, it results in False, as shown below:
False
Nand Function
This function performs Logical NAND operation. It evaluates its arguments and returns
True if any of them are False, and False if they are all True.
(True, False)
18
SymPy
Nor Function
This function performs Logical NOR operation. It evaluates its arguments and returns False
if any of them are True, and True if they are all False.
(False, False)
Note that even though SymPy provides ^ operator for Xor, ~ for Not, | for Or and & for
And functions as convenience, their normal use in Python is as bitwise operators. Hence,
if operands are integers, results would be different.
Equivalent function
This function returns equivalence relation. Equivalent(A, B) is True if and only if A and B
are both True or both False. The function returns True if all of the arguments are logically
equivalent. Returns False otherwise.
(False, True)
ITE function
This function acts as If then else clause in a programming language.ITE(A, B, C) evaluates
and returns the result of B if A is true else it returns the result of C. All args must be
Booleans.
(False, True)
19
11. SymPy ― Querying SymPy
The assumptions module in SymPy package contains tools for extracting information about
expressions. The module defines ask() function for this purpose.
sympy.assumptions.ask(property)
algebraic(x)
To be algebraic, a number must be a root of a non-zero polynomial equation with rational
coefficients. √2 because √2 is a solution to x2 − 2 = 0, so it is algebraic.
complex(x)
Complex number predicate. It is true if and only if x belongs to the set of complex
numbers.
composite(x)
Composite number predicate returned by ask(Q.composite(x)) is true if and only if x is a
positive integer and has at least one positive divisor other than 1 and the number itself.
even, odd
The ask() returns true of x is in the set of even numbers and set of odd numbers
respectively.
imaginary
This property represents Imaginary number predicate. It is true iff x can be written as a
real number multiplied by the imaginary unit I.
integer
This property returned by Q.integer(x) returns true of x belong to set of even numbers.
rational, irrational
Q.irrational(x) is true if and only if x is any real number that cannot be expressed as a
ratio of integers. For example, pi is an irrational number.
positive, negative
Predicates to check if number is positive or negative
zero, nonzero
Predicates to heck if a number is zero or not
20
SymPy
21
12. SymPy ― Simplification SymPy
Sympy has powerful ability to simplify mathematical expressions. There are many
functions in SymPy to perform various kinds of simplification. A general function called
simplify() is there that attempts to arrive at the simplest form of an expression.
simplify
This function is defined in sympy.simplify module. simplify() tries to apply intelligent
heuristics to make the input expression “simpler”. Following code shows simplifies
expression sin2(x)+cos2(x).
expand
The expand() is one of the most common simplification functions in SymPy, used in
expanding polynomial expressions. For example:
The above code snippet gives an output equivalent to the below expression:
𝒂𝟐 + 𝟐𝒂𝒃 + 𝒃𝟐
>>> expand((a+b)*(a-b))
The above code snippet gives an output equivalent to the below expression:
𝒂𝟐 − 𝒃𝟐
The expand() function makes expressions bigger, not smaller. Usually this is the case, but
often an expression will become smaller upon calling expand() on it.
−𝟐
22
SymPy
factor
This function takes a polynomial and factors it into irreducible factors over the rational
numbers.
The above code snippet gives an output equivalent to the below expression:
𝒛(𝒙 + 𝟐𝒚)𝟐
>>> factor(x**2+2*x+1)
The above code snippet gives an output equivalent to the below expression:
(𝒙 + 𝟏)𝟐
The factor() function is the opposite of expand(). Each of the factors returned by factor()
is guaranteed to be irreducible. The factor_list() function returns a more structured output.
The above code snippet gives an output equivalent to the below expression:
collect
This function collects additve terms of an expression with respect to a list of expression
up to powers with rational exponents.
The above code snippet gives an output equivalent to the below expression:
𝒙𝟑 − 𝒙𝟐 𝒛 + 𝟐𝒙𝟐 + 𝒙𝒚 + 𝒙 − 𝟑
The collect() function on this expression results as follows:
>>> collect(expr,x)
The above code snippet gives an output equivalent to the below expression:
𝒙𝟑 + 𝒙𝟐 (𝟐 − 𝒛) + 𝒙(𝒚 + 𝟏) − 𝟑
The above code snippet gives an output equivalent to the below expression:
23
SymPy
cancel
The cancel() function will take any rational function and put it into the standard canonical
form, p/q, where p and q are expanded polynomials with no common factors. The leading
coefficients of p and q do not have denominators i.e., they are integers.
>>> expr1=x**2+2*x+1
>>> expr2=x+1
>>> cancel(expr1/expr2)
The above code snippet gives an output equivalent to the below expression:
𝒙+𝟏
The above code snippet gives an output equivalent to the below expression:
𝟑𝒙
−𝟐 𝟏
𝟐 +
𝒙−𝟒 𝒙
>>> cancel(expr)
The above code snippet gives an output equivalent to the below expression:
𝟑𝒙𝟐 − 𝟐𝒙 − 𝟖
𝟐𝒙𝟐 − 𝟖𝒙
>>> expr=1/sin(x)**2
>>> expr1=sin(x)
>>> cancel(expr1*expr)
The above code snippet gives an output equivalent to the below expression:
𝟏
𝒔𝒊𝒏(𝒙)
trigsimp
This function is used to simplify trigonometric identities. It may be noted that naming
conventions for inverse trigonometric functions is to append an a to the front of the
function’s name. For example, the inverse cosine, or arc cosine, is called acos().
24
SymPy
𝟐
The trigsimp function uses heuristics to apply the best suitable trigonometric identity.
powersimp
This function reduces given expression by combining powers with similar bases and
exponents.
>>> expr=x**y*x**z*y**z
>>> expr
The above code snippet gives an output equivalent to the below expression:
𝒙𝒚 𝒙𝒛 𝒚𝒛
>>> powsimp(expr)
The above code snippet gives an output equivalent to the below expression:
𝒙𝒚+𝒛 𝒚𝒛
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.If force is
True then bases will be combined without checking for assumptions.
The above code snippet gives an output equivalent to the below expression:
𝒙𝒚 (𝒙𝒚)𝒛
combsimp
Combinatorial expressions involving factorial an binomials can be simplified by using
combsimp() function. SymPy provides a factorial() function
>>> expr=factorial(x)/factorial(x - 3)
>>> expr
The above code snippet gives an output equivalent to the below expression:
𝒙!
(𝒙 − 𝟑)!
To simplify above combinatorial expression we use combsimp() function as follows:
>>> combsimp(expr)
25
SymPy
The above code snippet gives an output equivalent to the below expression:
𝒙(𝒙 − 𝟐)(𝒙 − 𝟏)
The binomial(x, y) is the number of ways to choose y items from a set of x distinct items.
It is also often written as xCy.
>>> binomial(x,y)
The above code snippet gives an output equivalent to the below expression:
𝒙
( )
𝒚
>>> combsimp(binomial(x+1, y+1)/binomial(x, y))
The above code snippet gives an output equivalent to the below expression:
𝒙+𝟏
𝒚+𝟏
logcombine
This function takes logarithms and combines them using the following rules:
The above code snippet gives an output equivalent to the below expression:
The above code snippet gives an output equivalent to the below expression:
𝒙𝒂 𝒚
𝒍𝒐𝒈 ( )
𝒛
26
13. SymPy ― Derivative SymPy
The derivative of a function is its instantaneous rate of change with respect to one of its
variables. This is equivalent to finding the slope of the tangent line to the function at a
point.we can find the differentiation of mathematical expressions in the form of variables
by using diff() function in SymPy package.
diff(expr, variable)
The above code snippet gives an output equivalent to the below expression:
𝐱𝐬𝐢𝐧(𝐱 𝟐 ) + 𝟏
>>> diff(expr,x)
The above code snippet gives an output equivalent to the below expression:
The above code snippet gives an output equivalent to the below expression:
𝟐
𝟐𝒙𝒆𝒙
To take multiple derivatives, pass the variable as many times as you wish to differentiate,
or pass a number after the variable.
>>> diff(x**4,x,3)
The above code snippet gives an output equivalent to the below expression:
𝟐𝟒𝒙
4*x**3
12*x**2
24*x
27
SymPy
It is also possible to call diff() method of an expression. It works similarly as diff() function.
>>> expr=x*sin(x*x)+1
>>> expr.diff(x)
The above code snippet gives an output equivalent to the below expression:
The above code snippet gives an output equivalent to the below expression:
𝒅
(𝒙𝒔𝒊𝒏(𝒙𝟐 ) + 𝟏)
𝒅𝒙
>>> d.doit()
The above code snippet gives an output equivalent to the below expression:
28
14. SymPy ― Integration SymPy
The SymPy package contains integrals module. It implements methods to calculate definite
and indefinite integrals of expressions. The integrate() method is used to compute both
definite and indefinite integrals. To compute an indefinite or primitive integral, just pass
the variable after the expression.
For example:
integrate(f, x)
The above code snippet gives an output equivalent to the below expression:
𝒙𝟑 𝒙𝟐
+ +𝒙
𝟑 𝟐
>>> expr=sin(x)*tan(x)
>>> expr
>>> integrate(expr,x)
The above code snippet gives an output equivalent to the below expression:
𝒍𝒐𝒈(𝒔𝒊𝒏(𝒙) − 𝟏) 𝒍𝒐𝒈(𝒔𝒊𝒏(𝒙) + 𝟏)
− + − 𝒔𝒊𝒏(𝒙)
𝟐 𝟐
The example of definite integral is given below:
>>> expr=exp(-x**2)
>>> integrate(expr,(x,0,oo) )
The above code snippet gives an output equivalent to the below expression:
√𝝅
𝟐
29
SymPy
You can pass multiple limit tuples to perform a multiple integral. An example is given
below:
>>> integrate(expr,(x,0,oo),(y,0,oo))
The above code snippet gives an output equivalent to the below expression:
𝝅
𝟒
You can create unevaluated integral using Integral object, which can be evaluated by
calling doit() method.
The above code snippet gives an output equivalent to the below expression:
∫ 𝒍𝒐𝒈(𝒙)𝟐 𝒅𝒙
>>> expr.doit()
The above code snippet gives an output equivalent to the below expression:
𝒙𝒍𝒐𝒈(𝒙)𝟐 − 𝟐𝒙𝒍𝒐𝒈(𝒙) + 𝟐𝒙
Integral Transforms
SymPy supports various types of integral transforms as follows:
laplace_transform
fourier_transform
sine_transform
cosine_transform
hankel_transform
Example 1
>>> from sympy import fourier_transform, exp
>>> from sympy.abc import x, k
>>> expr=exp(-x**2)
>>> fourier_transform(expr, x, k)
30
SymPy
On executing the above command in python shell, following output will be generated:
sqrt(pi)*exp(-pi**2*k**2)
𝟐𝐤𝟐
√𝛑 ∗ 𝐞−𝛑
Example 2
>>> from sympy.integrals import laplace_transform
>>> from sympy.abc import t, s, a
>>> laplace_transform(t**a, t, s)
On executing the above command in python shell, following output will be generated:
31
15. SymPy ― Matrices SymPy
SymPy package has matrices module that deals with matrix handling. It includes Matrix
class whose object represents a matrix.
Note: If you want to execute all the snippets in this chapter individually, you
need to import the matrix module as shown below:
Example
>>> from sympy.matrices import Matrix
>>> m=Matrix([[1,2,3],[2,3,1]])
>>> m
$\displaystyle \left[\begin{matrix}1 & 2 & 3\\2 & 3 & 1\end{matrix}\right]$
On executing the above command in python shell, following output will be generated:
[𝟏 𝟐 𝟑 𝟐 𝟑 𝟏 ]
Matrix is created from appropriately sized List objects. You can also obtain a matrix by
distributing list items in specified number of rows and columns.
>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M
$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$
On executing the above command in python shell, following output will be generated:
[𝟏𝟎 𝟒𝟎 𝟑𝟎 𝟐 𝟔 𝟗 ]
Matrix is a mutable object. The matrices module also provides ImmutableMatrix class for
obtaining immutable matrix.
Basic manipulation
The shape property of Matrix object returns its size.
32
SymPy
>>> M.shape
(2, 3)
The row() and col() method respectively returns row or column of specified number.
>>> M.row(0)
$\displaystyle \left[\begin{matrix}10 & 40 & 30\end{matrix}\right]$
[𝟏𝟎 𝟒𝟎 𝟑𝟎 ]
>>> M.col(1)
$\displaystyle \left[\begin{matrix}40\\6\end{matrix}\right]$
[𝟒𝟎 𝟔 ]
Use Python's slice operator to fetch one or more items belonging to row or column.
>>> M.row(1)[1:3]
[6, 9]
Matrix class has row_del() and col_del() methods that deletes specified row/column from
given matrix:
>>> M=Matrix(2,3,[10,40,30,2,6,9])
>>> M.col_del(1)
>>> M
On executing the above command in python shell, following output will be generated:
You can apply style to the output using the following command:
You get the following output after executing the above code snippet:
[𝟏𝟎 𝟑𝟎 𝟐 𝟗 ]
>>> M.row_del(0)
>>> M
33
SymPy
You get the following output after executing the above code snippet:
[𝟐 𝟗 ]
Similarly, row_insert() and col_insert() methods add rows or columns at specified row or
column index
>>> M1=Matrix([[10,30]])
>>> M=M.row_insert(0,M1)
>>> M
$\displaystyle \left[\begin{matrix}10 & 30\\2 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet:
[𝟏𝟎 𝟑𝟎 𝟐 𝟗 ]
>>> M2=Matrix([40,6])
>>> M=M.col_insert(1,M2)
>>> M
$\displaystyle \left[\begin{matrix}10 & 40 & 30\\2 & 6 & 9\end{matrix}\right]$
You get the following output after executing the above code snippet:
[𝟏𝟎 𝟒𝟎 𝟑𝟎 𝟐 𝟔 𝟗 ]
Arithmetic Operations
Usual operators +, - and * are defined for performing addition, subtraction and
multiplication.
>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5,6],[6,5,4]])
>>> M1+M2
$\displaystyle \left[\begin{matrix}5 & 7 & 9\\9 & 7 & 5\end{matrix}\right]$
You get the following output after executing the above code snippet:
[𝟓 𝟕 𝟗 𝟗 𝟕 𝟓 ]
>>> M1-M2
34
SymPy
You get the following output after executing the above code snippet:
[−𝟑 − 𝟑 − 𝟑 − 𝟑 − 𝟑 − 𝟑 ]
Matrix multiplication is possible only if - The number of columns of the 1st matrix must
equal the number of rows of the 2nd matrix. - And the result will have the same number
of rows as the 1st matrix, and the same number of columns as the 2nd matrix.
>>> M1=Matrix([[1,2,3],[3,2,1]])
>>> M2=Matrix([[4,5],[6,6],[5,4]])
>>> M1*M2
$\displaystyle \left[\begin{matrix}31 & 29\\29 & 31\end{matrix}\right]$
[𝟑𝟏 𝟐𝟗 𝟐𝟗 𝟑𝟏 ]
Use T to obtain transpose as shown in the below code snippet:
>>> M1.T
$\displaystyle \left[\begin{matrix}1 & 3\\2 & 2\\3 & 1\end{matrix}\right]$
[𝟏 𝟑 𝟐 𝟐 𝟑 𝟏 ]
To calculate a determinant of matrix, use det() method. A determinant is a scalar value
that can be computed from the elements of a square matrix.
>>> M=Matrix(3,3,[10,20,30,5,8,12,9,6,15])
>>> M
$\displaystyle \left[\begin{matrix}10 & 20 & 30\\5 & 8 & 12\\9 & 6 &
15\end{matrix}\right]$
[𝟏𝟎 𝟐𝟎 𝟑𝟎 𝟓 𝟖 𝟏𝟐 𝟗 𝟔 𝟏𝟓 ]
>>> M.det()
35
SymPy
−𝟏𝟐𝟎
Matrix Constructors
SymPy provides many special type of matrix classes. For example, Identity matrix, matrix
of all zeroes and ones, etc. These classes are named as eye, zeros and ones respectively.
Identity matrix is a square matrix with elements falling on diagonal are set to 1, rest of
the elements are 0.
Example
from sympy.matrices import eye
eye(3)
Output
$\displaystyle \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 &
1\end{matrix}\right]$
[𝟏 𝟎 𝟎 𝟎 𝟏 𝟎 𝟎 𝟎 𝟏 ]
In diag matrix, elements on diagonal are initialized as per arguments provided.
[𝟏 𝟎 𝟎 𝟎 𝟐 𝟎 𝟎 𝟎 𝟑 ]
All elements in zeros matrix are initialized to 0.
[𝟎 𝟎 𝟎 𝟎 𝟎 𝟎 ]
36
SymPy
[𝟏 𝟏 𝟏 𝟏 𝟏 𝟏 ]
37
16. SymPy ― Function class SymPy
re
This function returns real part of an expression:
>>> re(I)
Im
This function returns imaginary part of an expression:
>>> im(5+3*I)
>>> im(I)
sign
This function returns the complex sign of an expression.
1 if expression is positive
0 if expression is equal to zero
-1 if expression is negative
I if im(expression) is positive
-I if im(expression) is negative
(1, -1, 0)
(-I, I)
Abs
This function return absolute value of a complex number. It is defined as the distance
between the origin (0,0) and the point (a,b) in the complex plane. This function is an
extension of the built-in function abs() to accept symbolic values.
>>> Abs(2+3*I)
√𝟏𝟑
conjugate
This function returns conjugate of a complex number. To find the complex conjugate we
change the sign of the imaginary part.
>>> conjugate(4+7*I)
You get the following output after executing the above code snippet:
𝟒 − 𝟕𝒊
39
SymPy
Trigonometric functions
SymPy has defintions for all trigonometric ratios - sin cos, tan etc as well as well as its
inverse counterparts such as asin, acos, atan etc. These functions compute respective
value for given angle expressed in radians.
ceiling
This is a univariate function which returns the smallest integer value not less than its
argument. In case of complex numbers, ceiling of the real and imaginary parts separately.
(4, 7, 3 + 4*I)
floor
This function returns the largest integer value not greater than its argument. In case of
complex numbers, this function too takes the floor of the real and imaginary parts
separately.
frac
This function represents the fractional part of x.
40
SymPy
(0.990000000000000, 1/3, 0)
Combinatorial functions
Combinatorics is a field of mathematics concerned with problems of selection,
arrangement, and operation within a finite or discrete system.
factorial
The factorial is very important in combinatorics where it gives the number of ways in which
n objects can be permuted. It is symbolically represented as 𝑥! This function is
implementation of factorial function over nonnegative integers, factorial of a negative
integer is complex infinity.
>>> x=Symbol('x')
>>> factorial(x)
𝒙!
>>> factorial(5)
𝟏𝟐𝟎
>>> factorial(-1)
∞~
binomial
This function the number of ways we can choose k elements from a set of n elements.
𝒙
( )
𝒚
>>> binomial(4,2)
𝟔
Rows of Pascal’s triangle can be generated with the binomial function.
41
SymPy
You get the following output after executing the above code snippet:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
fibonacci
The Fibonacci numbers are the integer sequence defined by the initial terms F0=0, F1=1
and the two-term recurrence relation Fn=Fn−1+Fn−2.
The following output is obtained after executing the above code snippet:
tribonacci
The Tribonacci numbers are the integer sequence defined by the initial terms F 0=0, F1=1,
F2=1 and the three-term recurrence relation Fn=Fn-1+Fn-2+Fn-3.
The above code snippet gives an output equivalent to the below expression:
𝐱 𝟖 + 𝟑𝐱 𝟓 + 𝟑𝐱 𝟐
The following output is obtained after executing the above code snippet:
42
SymPy
Miscellaneous Functions
Following is a list of some frequently used functions:
Min: Returns minimum value of the list. It is named Min to avoid conflicts with the built-
in function min.
Max: Returns maximum value of the list. It is named Max to avoid conflicts with the built-
in function max.
cbrt: This function computes the principal cube root of x, (shortcut for x∗∗Rational(1,3)).
The following are the examples of the above miscellaneous functions and their respective
outputs:
>>> Min(pi,E)
𝟏𝟏
𝟐
>>> root(7,Rational(1,2))
𝟒𝟗
>>> sqrt(2)
√𝟐
>>> cbrt(1000)
𝟏𝟎
43
17. SymPy ― Quaternion SymPy
q=a+bi+cj+dk
where a, b, c and d are real numbers and i, j, k are quaternion units such that,
i2==j2==k2==ijk
The above code snippet gives an output equivalent to the below expression:
𝟐 + 𝟑𝒊 + 𝟏𝒋 + 𝟒𝒌
Quaternions are used in pure mathematics, as well as in applied mathematics, computer
graphics, computer vision, etc.
The above code snippet gives an output equivalent to the below expression:
𝒙𝟐 + 𝒙𝟑 𝒊 + 𝒙𝒋 + 𝟎𝒌
Quaternion object can also have imaginary co-efficients
The above code snippet gives an output equivalent to the below expression:
𝟐 + (𝟑 + 𝟐𝒊)𝒊 + 𝒙𝟐 𝒋 + 𝟑. 𝟓𝒊𝒌
add()
This method available in Quaternion class performs addition of two Quaternion objects.
44
SymPy
>>> q1=Quaternion(1,2,3,4)
>>> q2=Quaternion(4,3,2,1)
>>> q1.add(q2)
The above code snippet gives an output equivalent to the below expression:
𝟓 + 𝟓𝒊 + 𝟓𝒋 + 𝟓𝒌
It is possible to add a number or symbol in a Quaternion object.
>>> q1+2
The following output is obtained after executing the above code snippet:
𝟑 + 𝟐𝒊 + 𝟑𝒋 + 𝟒𝒌
>>> q1+x
The following output is obtained after executing the above code snippet:
(𝒙 + 𝟏) + 𝟐𝒊 + 𝟑𝒋 + 𝟒𝒌
mul()
This method performs multiplication of tqo quaternion objects.
>>> q1=Quaternion(1,2,1,2)
>>> q2=Quaternion(2,4,3,1)
>>> q1.mul(q2)
The above code snippet gives an output equivalent to the below expression:
(−𝟏𝟏) + 𝟑𝒊 + 𝟏𝟏𝒋 + 𝟕𝒌
inverse()
This method returns inverse of a quaternion object.
>>> q1.inverse()
The above code snippet gives an output equivalent to the below expression:
𝟏 𝟏 𝟏 𝟏
+ (− ) 𝒊 + (− ) 𝒋 + (− ) 𝒌
𝟏𝟎 𝟓 𝟏𝟎 𝟓
pow()
This method returns power of a quaternion object.
>>> q1.pow(2)
45
SymPy
The following output is obtained after executing the above code snippet:
(−𝟖) + 𝟒𝒊 + 𝟐𝒋 + 𝟒𝒌
exp()
This method computes exponential of a Quaternion object i.e. eq
>>> q=Quaternion(1,2,4,3)
>>> q.exp()
The following output is obtained after executing the above code snippet:
46
18. SymPy ― Solvers SymPy
Since the symbols = and == are defined as assignment and equality operators in Python,
they cannot be used to formulate symbolic equations. SymPy provides Eq() function to set
up an equation.
The above code snippet gives an output equivalent to the below expression:
𝒙=𝒚
Since x=y is possible if and only if x-y=0, qbove equation can be written as:
>>> Eq(x-y,0)
The above code snippet gives an output equivalent to the below expression:
𝒙−𝒚=𝟎
The solver module in SymPy provides soveset() function whose prototype is as follows:
The domain is by default S.Complexes. Using solveset() function, we can solve an algebraic
equation as follows:
>>> solveset(Eq(x**2-9,0), x)
{−𝟑, 𝟑}
The following output is obtained after executing the above code snippet:
{𝟏, 𝟐}
The output of solveset is a FiniteSet of the solutions. If there are no solutions, an EmptySet
is returned
>>> solveset(exp(x),x)
The following output is obtained after executing the above code snippet:
47
SymPy
Linear equation
We have to use linsolve() function to solve linear equations.
x-y=4
x+y=1
The following output is obtained after executing the above code snippet:
𝟓 𝟑
{( , − )}
𝟐 𝟐
The linsolve() function can also solve linear equations expressed in matrix form.
𝟓 𝟑
{( , − )}
𝟐 𝟐
Non-linear equation
For this purpose, we use nonlinsolve() function. Equations for this example:
a2+a=0 a-b=0
differential equation
First, create an undefined function by passing cls=Function to the symbols function. To
solve differential equations, use dsolve.
>>> x=Symbol('x')
>>> f=symbols('f', cls=Function)
>>> f(x)
The following output is obtained after executing the above code snippet:
48
SymPy
𝒇(𝒙)
Here f(x) is an unevaluated function. Its derivative is as follows:
>>> f(x).diff(x)
The above code snippet gives an output equivalent to the below expression:
𝒅
𝒇(𝒙)
𝒅𝒙
We first create Eq object corresponding to following differential equation
The above code snippet gives an output equivalent to the below expression:
𝒅
−𝒇(𝒙) + 𝒇(𝒙) = 𝒔𝒊𝒏(𝒙)
𝒅𝒙
>>> dsolve(eqn, f(x))
The above code snippet gives an output equivalent to the below expression:
49
19. SymPy ― Plotting SymPy
SymPy uses Matplotlib library as a backend to render 2-D and 3-D plots of mathematical
functions. Ensure that Matplotlib is available in current Python installation. If not, install
the same using following command:
The plot() function returns an instance of Plot class. A plot figure may have one or more
SymPy expressions. Although it is capable of using Matplotlib as backend, other backends
such as texplot, pyglet or Google charts API may also be used.
where expr is any valid symPy expression. If not mentioned, range uses default as (-10,
10).
50
SymPy
To draw multiple plots for same range, give multiple expressions prior to the range tuple.
51
SymPy
52
SymPy
53
SymPy
As in 2D plot, a three dimensional plot can also have multiple plots each with different
range.
54
SymPy
55
SymPy
56
20. SymPy ― Entities SymPy
The geometry module in SymPy allows creation of two dimensional entities such as line,
circle, etc. We can then obtain information about them such as checking colinearity or
finding intersection.
Point
Point class represents a point in Euclidean space. Following example checks for collinearity
of points:
Output
True
>>> a=Point(2,3)
>>> Point.is_collinear(x,y,a)
Output
False
The distance() method of Point class calculates distance between two points
>>> x.distance(y)
Output
𝟐√𝟐
The distance may also be represented in terms of symbols.
Line
Line entity is obtained from two Point objects. The intersection() method returns point of
intersection if two lines intersect each other.
57
SymPy
Output
[Point2D(5/2, 5/2)]
Output
[Point2D(5/2, 5/2)]
>>> x,y=symbols('x y')
>>> p=Point(x,y)
>>> p.distance(Point(0,0))
Output
√𝒙𝟐 + 𝒚𝟐
Triangle
This function builds a triangle entity from three point objects.
Triangle(a,b,c)
Output
𝟐𝟓
−
𝟐
Ellipse
An elliptical geometry entity is constructed by passing a Point object corresponding to
center and two numbers each for horizontal and vertical radius.
Output
𝟐𝟒𝝅
The vradius can be indirectly provided by using eccentricity parameter.
58
SymPy
Output
𝟓√ 𝟕
𝟒
The apoapsis of the ellipse is the greatest distance between the focus and the contour.
>>> e1.apoapsis
Output
𝟑𝟓
𝟒
Following statement calculates circumference of ellipse:
>>> e1.circumference
Output
𝟗
𝟐𝟎𝑬 ( )
𝟏𝟔
The equation method of ellipse returns equation of ellipse.
>>> e1.equation(x,y)
Output
𝒙 𝟐 𝟐 𝟏𝟔(𝒚 − 𝟐)𝟐
( − ) + −𝟏
𝟓 𝟓 𝟏𝟕𝟓
59
21. SymPy ― Sets SymPy
Set is a base class for any other type of set in SymPy. Note that it is different from built-
in set data type of Python. Interval class represents real intervals and its boundary
property returns a FiniteSet object.
sympy.sets.sets.FiniteSet
FiniteSet is a collection of discrete numbers. It can be obtained from any sequence object
such as list or string.
Output
{{𝟎, 𝟏, … , 𝟒}}
>>> numbers=[1,3,5,2,8]
>>> FiniteSet(*numbers)
Output
{𝟏, 𝟐, 𝟑, 𝟓, 𝟖}
>>> s="HelloWorld"
>>> FiniteSet(*s)
Output
{𝑯, 𝑾, 𝒅, 𝒆, 𝒍, 𝒐, 𝒓}
Note that, as in built-in set, SymPy's Set is also a collection of distinct objects.
60
SymPy
Output
{𝐱 ∣ 𝐱 ∈ [𝟏, 𝟏𝟎] ∧ 𝐱 𝟐 − 𝟐𝐱 = 𝟎}
Union is a compound set. It includes all elements in two sets. Note that elements that are
found in both, will appear only once in the Union.
Intersection on the other hand contains only those elements that are present in both.
Complement(a,b) retains elements in a excluding elements that are common with b set.
Output
{𝟐, 𝟑, 𝟓, 𝟗}
61
22. SymPy — Printing SymPy
str
srepr
ASCII pretty printer
Unicode pretty printer
LaTeX
MathML
Dot
SymPy objects can also be sent as output to code of various languages, such as C, Fortran,
Javascript, Theano, and Python.
SymPy uses Unicode characters to render output in form of pretty print. If you are using
Python console for executing SymPy session, the best pretty printing environment is
activated by calling init_session() function.
IPython console for SymPy 1.5.1 (Python 3.7.4-64-bit) (ground types: python).
>>> Integral(sqrt(1/x),x)
𝟏
∫ √ 𝒅𝒙
𝒙
If LATEX is not installed, but Matplotlib is installed, it will use the Matplotlib rendering
engine. If Matplotlib is not installed, it uses the Unicode pretty printer. However, Jupyter
notebook uses MathJax to render LATEX.
62
SymPy
In a terminal that does not support Unicode, ASCII pretty printer is used.
To use ASCII printer use pprint() function with use_unicode property set to False
>>> pprint(Integral(sqrt(1/x),x),use_unicode=False)
The Unicode pretty printer is also accessed from pprint() and pretty(). If the terminal
supports Unicode, it is used automatically. If pprint() is not able to detect that the terminal
supports unicode, you can pass use_unicode=True to force it to use Unicode.
>>> print(latex(Integral(sqrt(1/x),x)))
\int \sqrt{\frac{1}{x}}\, dx
You can also use mathml printer. for that purpose, import print_mathml function. A string
version is obtained by mathml() function.
63
SymPy
<apply>
<int/>
<bvar>
<ci>x</ci>
</bvar>
<apply>
<root/>
<apply>
<power/>
<ci>x</ci>
<cn>-1</cn>
</apply>
</apply>
</apply>
>>> mathml(Integral(sqrt(1/x),x))
'<apply><int/><bvar><ci>x</ci></bvar><apply><root/><apply><power/
><ci>x</ci><cn>-1</cn></apply></apply></apply>'
64