Tutorial
From SymPy
Contents |
Introduction
This tutorial gives an overview and introduction to SymPy. Read this to have an idea what SymPy can do for you (and how) and if you want to know more, read the API documentation (that is generated from the sources) or the sources directly.
Installation
See the Downloads tab and follow the instructions specific to your platform.
Importing SymPy
To import SymPy from the standard Python shell, just type
<source lang="python"> >>> from sympy import * </source>
and most common functions will be imported. Other modules of interest include sympy.limits, sympy.solvers, etc.
There is also a little app called isympy (located in bin/isympy if you are running from the source directory) which is just a standard Python shell that has already imported the relevant SymPy modules and defined the symbols x, y and z.
Using SymPy as a calculator
Sympy has two built-in numeric types: Real and Rational.
The Rational class represents a rational number as a pair of two integers: the numerator and the denominator, so Rational(1,2) represents 1/2, Rational(5,2) 5/2 and so on.
<source lang="python"> >>> from sympy import * >>> a = Rational(1,2)
>>> a 1/2
>>> a*2 1
>>> Rational(2)**50/Rational(10)**50 1/88817841970012523233890533447265625 </source>
Proceed with caution while working with Python's int since they truncate integer division, and that's why:
<source lang="python"> >>> 1/2 0
>>> 1.0/2 0.5 </source>
You can however do:
<source lang="python"> >>> from __future__ import division
>>> 1/2 #doctest: +SKIP 0.5 </source>
It's going to be standard in Python, hopefully soon...
We also have some special constants, like e and pi, that are treated as symbols (1+pi won't evaluate to something numeric, rather it will remain as 1+pi), and have arbitrary precision:
<source lang="python"> >>> pi**2 pi**2
>>> pi.evalf() 3.141592653589793238462643383
>>> (pi+exp(1)).evalf() 5.859874482049203234066343309 </source>
As you see, evalf evaluates the expression to a floating-point number.
There is also a class representing mathematical infinity, called oo:
<source lang="python"> >>> oo > 99999 True >>> oo + 1 oo </source>
Symbols
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly:
<source lang="python"> >>> from sympy import * >>> x = Symbol('x') >>> y = Symbol('y') </source>
Then you can play with them:
<source lang="python"> >>> x+y+x-y 2*x
>>> (x+y)**2 (x+y)**2
>>> ((x+y)**2).expand() 2*x*y+x**2+y**2 </source>
And substitute them for other symbols or numbers using subs(var, substitution):
<source lang="python"> >>> ((x+y)**2).subs(x, 1) (1+y)**2
>>> ((x+y)**2).subs(x, y) 4*y**2 </source>
Calculus
Limits
Limits are easy to use in SymPy. They follow the syntax limit(function, variable, point), so to compute the limit of f(x) as x -> 0, you would issue limit(f, x, 0).
<source lang="python"> >>> from sympy import * >>> x=Symbol("x") >>> limit(sin(x)/x, x, 0) 1 </source>
You can also calculate the limit at infinity:
<source lang="python"> >>> limit(x, x, oo) oo
>>> limit(1/x, x, oo) 0
>>> limit(x**x, x, 0) 1
>>> limit((5**x+3**x)**(1/x), x, oo) 5 </source>
For some non-trivial examples on limits, you can read the test file test_demidovich.py.
Differentiation
You can differentiate any SymPy expression using diff(func, var). Examples:
<source lang="python"> >>> from sympy import * >>> x = Symbol('x') >>> diff(sin(x), x) cos(x) >>> diff(sin(2*x), x) 2*cos(2*x)
>>> diff(tan(x), x) cos(x)**(-2) </source>
You can check, that it is correct by:
<source lang="python"> >>> limit((tan(x+y)-tan(x))/y, y, 0) cos(x)**(-2) </source>
Higher derivatives can be calculated using the diff(func, var, n) method:
<source lang="python"> >>> diff(sin(2*x), x, 1) 2*cos(2*x)
>>> diff(sin(2*x), x, 2) -4*sin(2*x)
>>> diff(sin(2*x), x, 3) -8*cos(2*x) </source>
Series expansion
Use .series(var, order):
<source lang="python"> >>> from sympy import * >>> x = Symbol('x') >>> cos(x).series(x, 0, 10) 1 - 1/2*x**2 + (1/24)*x**4 - 1/720*x**6 + (1/40320)*x**8 + O(x**10) >>> (1/cos(x)).series(x, 0, 10) 1 + (1/2)*x**2 + (5/24)*x**4 + (61/720)*x**6 + (277/8064)*x**8 + O(x**10) </source>
Integration
SymPy has support for indefinite and definite integration of transcendental elementary and special functions via integrate() facility, which uses powerful extended Risch-Norman algorithm and some heuristics and pattern matching.
<source lang="python"> >>> from sympy import * >>> x, y = symbols('xy') </source>
You can integrate elementary functions:
<source lang="python"> >>> integrate(6*x**5, x) x**6 >>> integrate(sin(x), x) -cos(x) >>> integrate(log(x), x) x*log(x) - x >>> integrate(2*x + sinh(x), x) x**2 + cosh(x) </source>
Also special functions are handled easily:
<source lang="python"> >>> integrate(exp(-x**2)*erf(x), x) (1/4)*pi**(1/2)*erf(x)**2 </source>
It is possible to compute definite integral:
<source lang="python"> >>> integrate(x**3, (x, -1, 1)) 0 >>> integrate(sin(x), (x, 0, pi/2)) 1 >>> integrate(cos(x), (x, -pi/2, pi/2)) 2 </source>
Also improper integrals are supported as well:
<source lang="python"> >>> integrate(exp(-x), (x, 0, oo)) 1 >>> integrate(log(x), (x, 0, 1)) -1 </source>
Complex numbers
<source lang="python"> >>> from sympy import Symbol, exp, I >>> x = Symbol("x") >>> exp(I*x).expand() exp(I*x) >>> exp(I*x).expand(complex=True) 1/exp(im(x))*cos(re(x)) + I/exp(im(x))*sin(re(x)) >>> x = Symbol("x", real=True) >>> exp(I*x).expand(complex=True) I*sin(x) + cos(x) </source>
Differential equations
In isympy: <source lang="python"> In [9]: f(x).diff(x, x) + f(x) == 0 Out[9]:
2 d
─────(f(x)) + f(x) = 0 dx dx
In [10]: dsolve(f(x).diff(x, x) + f(x) == 0, f(x)) Out[10]: Câ‚*sin(x) + Câ‚‚*cos(x) </source>
Algebraic equations
In isympy: <source lang="python"> In [19]: solve(x**4 == 1, x) Out[19]: [â…ˆ, 1, -1, -â…ˆ]
In [20]: solve([x + 5*y == 2, -3*x + 6*y == 15], [x, y]) Out[20]: {y: 1, x: -3} </source>
Linear Algebra
Matrices
Matrices are created as instances from the Matrix class. This class is located in sympy.matrices, but at usual, isympy imports this for you:
<source lang="python"> >>> from sympy import * >>> from sympy.matrices import Matrix >>> Matrix([[1,0], [0,1]]) [1, 0] [0, 1]
</source>
You can also put symbols in it: <source lang="python"> >>> x = Symbol('x') >>> y = Symbol('y') >>> A = Matrix([[1,x], [y,1]]) >>> A [1, x] [y, 1]
>>> A**2 [1 + x*y, 2*x] [ 2*y, 1 + x*y] </source>
For more information and examples with matrices, see the Linear Algebra tutorial.
Pattern matching
Use the .match() method, along with the Wild class, to perform pattern matching on expressions. The method will return a dictionary with the required substitutions, as follows:
<source lang="python"> >>> from sympy import * >>> x = Symbol('x') >>> p = Wild('p') >>> q = Wild('q') >>> (5*x**2 + 3*x).match(p*x**2 + q*x) {p_: 5, q_: 3}
>>> (x**2).match(p*x**q) {p_: 1, q_: 2} </source>
If the match is unsuccessful, it returns None:
<source lang="python"> >>> print (x+1).match(p**x) None </source>
One can also make use of the WildFunction class to perform more specific matches with functions and their arguments:
<source lang="python"> >>> f = WildFunction('f', nofargs=1) >>> (5*cos(x)).match(p*f) {p_: 5, f_: cos(x)} >>> (cos(3*x)).match(f(p*x)) {p_: 3, f_: cos} >>> g = WildFunction('g', nofargs=2) >>> (5*cos(x)).match(p*g) None </source>
One can also use the exclude parameter of the Wild class to ensure that certain things do not show up in the result:
<source lang="python"> >>> x = Symbol('x') >>> p = Wild('p', exclude=[1,x]) >>> print (x+1).match(x+p) # 1 is excluded None >>> print (x+1).match(p+1) # x is excluded None >>> print (x+1).match(x+2+p) # -1 is not excluded {p_: -1} </source>
Printing
SymPy comes pre-packed with several ways of printing expressions. The most basic way to print an expression is simply though the use of str(expression) or repr(expression). The output of repr(expression) can vary depending on the representation level set. By default it is set to level 1, but can be set through the Basic.set_repr_level function. The available levels are:
- Level 0, the lowest printing level. Expressions are printed in such a way that they should be able to be evaluated with Python's eval() function.
- Level 1, the default printing level. Expressions are printed in a parsable format, but cannot necessarily be passed to Python's eval() method. This level is much more readable than Level 0 and is useful for interactive use.
- Level 2, the highest printing level. Expressions are printed in a two-dimensional plain text format that is intended only for readability.
<source lang="python"> >>> from sympy import * >>> for level in xrange(0, 3): ... oldlevel = Basic.set_repr_level(level) ... print repr(Rational(101,123)) ... print ... Rational(101, 123)
101/123
101 --- 123
>>> </source>
Note that there is also a printing module available, sympy.printing. Level 2 printing is made possible through the pretty printing component of the printing module. Other printing methods available trough this module are:
- pretty(expr), pretty_print(expr), pprint(expr)
- Return or print, respectively, a pretty representation of expr. This is the same as the second level of representation described above.
- latex(expr), print_latex(expr)
- Return or print, respectively, a LaTeX representation of expr.
- mathml(expr), print_mathml(expr)
- Return or print, respectively, a MathML representation of expr.
- print_gtk(expr)
- Print expr to Gtkmathview, a GTK widget that displays MathML code. The Gtkmathview program is required.
- print_pygame(expr)
Modules
The following list provides links to documentation for some of the various modules SymPy offers
