7 .. role:: input(strong)
12 SymPy is a Python library for symbolic mathematics. It aims to become a
13 full-featured computer algebra system (CAS) while keeping the code as simple as
14 possible in order to be comprehensible and easily extensible. SymPy is written
15 entirely in Python and does not require any external libraries.
17 This tutorial gives an overview and introduction to SymPy.
18 Read this to have an idea what SymPy can do for you (and how) and if you want
19 to know more, read the
20 :ref:`SymPy User's Guide <guide>`,
21 :ref:`SymPy Modules Reference <module-docs>`.
23 <http://hg.sympy.org/sympy/file/tip>`_ directly.
25 First Steps with SymPy
26 ======================
28 The easiest way to download it is to go to
29 http://code.google.com/p/sympy/ and
30 download the latest tarball from the Featured Downloads:
32 .. image:: figures/featured-downloads.png
38 $ :input:`tar xzf sympy-0.5.12.tar.gz`
40 and try it from a Python intepreter:
44 $ :input:`cd sympy-0.5.12`
46 Python 2.4.4 (#2, Jan 3 2008, 13:36:28)
47 [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2
48 Type "help", "copyright", "credits" or "license" for more information.
49 >>> :input:`from sympy import Symbol, cos`
50 >>> :input:`x = Symbol("x")`
51 >>> :input:`(1/cos(x)).series(x, 0, 10)`
52 1 + (1/2)*x**2 + (5/24)*x**4 + (61/720)*x**6 + (277/8064)*x**8 + O(x**10)
54 You can use SymPy as shown above and this is indeed the recommended way if you
55 use it in your program. You can also install it using ``./setup.py install`` as
56 any other Python module, or just install a package in your favourite Linux
59 .. topic:: Installing SymPy in Debian
63 $ :input:`sudo apt-get install python-sympy`
64 Reading package lists... Done
65 Building dependency tree
66 Reading state information... Done
67 The following NEW packages will be installed:
69 0 upgraded, 1 newly installed, 0 to remove and 18 not upgraded.
70 Need to get 991kB of archives.
71 After this operation, 5976kB of additional disk space will be used.
72 Get:1 http://ftp.cz.debian.org unstable/main python-sympy 0.5.12-1 [991kB]
73 Fetched 991kB in 2s (361kB/s)
74 Selecting previously deselected package python-sympy.
75 (Reading database ... 232619 files and directories currently installed.)
76 Unpacking python-sympy (from .../python-sympy_0.5.12-1_all.deb) ...
77 Setting up python-sympy (0.5.12-1) ...
80 For other means how to install SymPy, consult the Downloads_ tab on the
83 .. _Downloads: http://code.google.com/p/sympy/wiki/DownloadInstallation?tm=2
89 For experimenting with new features, or when figuring out how to do things, you
90 can use our special wrapper around IPython called ``isympy`` (located in
91 ``bin/isympy`` if you are running from the source directory) which is just a
92 standard python shell that has already imported the relevant sympy modules and
93 defined the symbols x, y, z and some other things:
97 $ :input:`cd sympy-0.5.12`
99 Python 2.4.4 console for SymPy 0.5.12-hg. These commands were executed:
100 >>> from __future__ import division
101 >>> from sympy import *
102 >>> x, y, z = symbols('xyz')
103 >>> k, m, n = symbols('kmn', integer=True)
104 >>> f = Function("f")
106 Documentation can be found at http://sympy.org/
109 In [1]: :input:`(1/cos(x)).series(x, 0, 10)`
113 1 + ── + ──── + ───── + ────── + O(x**10)
118 Commands entered by you are bold. Thus what we did in 3 lines in a regular
119 Python interpeter can be done in 1 line in isympy.
122 Using SymPy as a calculator
123 ---------------------------
125 Sympy has three built-in numeric types: Real, Rational and Integer.
127 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.
131 >>> from sympy import *
132 >>> a = Rational(1,2)
140 >>> Rational(2)**50/Rational(10)**50
141 1/88817841970012523233890533447265625
144 proceed with caution while working with python int's since they truncate
145 integer division, and that's why::
155 >>> from __future__ import division
157 >>> 1/2 #doctest: +SKIP
160 True division is going to be standard in python3k and ``isympy`` does that too.
162 We also have some special constants, like e and pi, that are treated as symbols
163 (1+pi won't evaluate to something numeric, rather it will remain as 1+pi), and
164 have arbitrary precission::
170 3.141592653589793238462643383
172 >>> (pi+exp(1)).evalf()
173 5.859874482049203234066343309
175 as you see, evalf evaluates the expression to a floating-point number
177 There is also a class representing mathematical infinity, called ``oo``::
187 In contrast to other Computer Algebra Systems, in SymPy you have to declare
188 symbolic variables explicitly::
190 >>> from sympy import *
194 Then you can play with them::
202 >>> ((x+y)**2).expand()
205 And substitute them for other symbols or numbers using ``subs(old, new)``::
207 >>> ((x+y)**2).subs(x, 1)
210 >>> ((x+y)**2).subs(x, y)
216 For partial fraction decomposition, use ``apart(expr, x)``::
218 In [1]: 1/( (x+2)*(x+1) )
224 In [2]: apart(1/( (x+2)*(x+1) ), x)
236 In [4]: apart((x+1)/(x-1), x)
242 To combine things back together, use ``together(expr, x)``::
244 In [7]: together(1/x + 1/y + 1/z)
250 In [8]: together(apart((x+1)/(x-1), x), x)
256 In [9]: together(apart(1/( (x+2)*(x+1) ), x), x)
273 Limits are easy to use in sympy, they follow the syntax limit(function,
274 variable, point), so to compute the limit of f(x) as x -> 0, you would issue
277 >>> from sympy import *
279 >>> limit(sin(x)/x, x, 0)
282 you can also calculate the limit at infinity::
287 >>> limit(1/x, x, oo)
290 >>> limit(x**x, x, 0)
293 for some non-trivial examples on limits, you can read the test file
295 <http://hg.sympy.org/sympy/file/tip/sympy/series/tests/test_demidovich.py>`_
297 .. index:: differentiation, diff
302 You can differentiate any SymPy expression using ``diff(func, var)``. Examples::
304 >>> from sympy import *
308 >>> diff(sin(2*x), x)
314 You can check, that it is correct by::
316 >>> limit((tan(x+y)-tan(x))/y, y, 0)
319 Higher derivatives can be calculated using the ``diff(func, var, n)`` method::
321 >>> diff(sin(2*x), x, 1)
324 >>> diff(sin(2*x), x, 2)
327 >>> diff(sin(2*x), x, 3)
332 single: series expansion
333 single: expansion; series
338 Use ``.series(var, point, order)``::
340 >>> from sympy import *
342 >>> cos(x).series(x, 0, 10)
343 1 - 1/2*x**2 + (1/24)*x**4 - 1/720*x**6 + (1/40320)*x**8 + O(x**10)
344 >>> (1/cos(x)).series(x, 0, 10)
345 1 + (1/2)*x**2 + (5/24)*x**4 + (61/720)*x**6 + (277/8064)*x**8 + O(x**10)
347 Another simple example::
349 from sympy import Integral, Symbol, pprint
355 s = e.series(x, 0, 5)
360 That should print the following after the execution::
362 1/y + x**2*y**(-3) + x**4*y**(-5) - x*y**(-2) - x**3*y**(-4) + O(x**5)
365 ─ + ── + ── - ── - ── + O(x**5)
369 .. index:: integration
374 SymPy has support for indefinite and definite integration of transcendental
375 elementary and special functions via `integrate()` facility, which uses
376 powerful extended Risch-Norman algorithm and some heuristics and pattern
379 >>> from sympy import *
380 >>> x, y = symbols('xy')
382 You can integrate elementary functions::
384 >>> integrate(6*x**5, x)
386 >>> integrate(sin(x), x)
388 >>> integrate(log(x), x)
390 >>> integrate(2*x + sinh(x), x)
393 Also special functions are handled easily::
395 >>> integrate(exp(-x**2)*erf(x), x)
396 (1/4)*pi**(1/2)*erf(x)**2
398 It is possible to compute definite integral::
400 >>> integrate(x**3, (x, -1, 1))
402 >>> integrate(sin(x), (x, 0, pi/2))
404 >>> integrate(cos(x), (x, -pi/2, pi/2))
407 Also improper integrals are supported as well::
409 >>> integrate(exp(-x), (x, 0, oo))
411 >>> integrate(log(x), (x, 0, 1))
415 single: complex numbers
416 single: expansion; complex
423 >>> from sympy import Symbol, exp, I
425 >>> exp(I*x).expand()
427 >>> exp(I*x).expand(complex=True)
428 1/exp(im(x))*cos(re(x)) + I/exp(im(x))*sin(re(x))
429 >>> x = Symbol("x", real=True)
430 >>> exp(I*x).expand(complex=True)
438 In [1]: sin(x+y).expand(trig=True)
439 Out[1]: cos(x)*sin(y) + cos(y)*sin(x)
441 In [2]: cos(x+y).expand(trig=True)
442 Out[2]: cos(x)*cos(y) - sin(x)*sin(y)
459 In [15]: sin(x).series(x, 0, 10)
463 x - ── + ─── - ──── + ────── + O(x**10)
466 In [16]: sinh(x).series(x, 0, 10)
470 x + ── + ─── + ──── + ────── + O(x**10)
473 In [17]: asin(x).series(x, 0, 10)
477 x + ── + ──── + ──── + ───── + O(x**10)
480 In [18]: asinh(x).series(x, 0, 10)
484 x - ── + ──── - ──── + ───── + O(x**10)
488 **spherical harmonics**::
490 In [1]: from sympy.abc import theta, phi
492 In [2]: Ylm(1, 0, theta, phi)
500 In [3]: Ylm(1, 1, theta, phi)
508 In [4]: Ylm(2, 1, theta, phi)
511 -╲╱ 30 *│sin(θ)│*cos(θ)*ℯ
512 ────────────────────────────
516 **factorials and gamma function**::
518 In [1]: x = Symbol("x")
520 In [2]: y = Symbol("y", integer=True)
528 In [5]: factorial(x).series(x, 0, 3)
532 1 - x*EulerGamma + ────────────── + ───── + O(x**3)
564 In [1]: chebyshevt(2, x)
569 In [2]: chebyshevt(4, x)
574 In [3]: legendre(2, x)
581 In [4]: legendre(8, x)
584 35 315*x 3465*x 3003*x 6435*x
585 ─── - ────── + ─────── - ─────── + ───────
588 In [5]: assoc_legendre(2, 1, x)
594 In [6]: assoc_legendre(2, 2, x)
599 In [7]: hermite(3, x)
605 .. index:: equations; differential, diff, dsolve
607 Differential Equations
608 ----------------------
612 In [4]: f(x).diff(x, x) + f(x)
619 In [5]: dsolve(f(x).diff(x, x) + f(x), f(x))
620 Out[5]: C₁*sin(x) + C₂*cos(x)
623 .. index:: equations; algebraic, solve
630 In [7]: solve(x**4 - 1, x)
631 Out[7]: [ⅈ, 1, -1, -ⅈ]
633 In [8]: solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
634 Out[8]: {y: 1, x: -3}
637 .. index:: linear algebra
647 Matrices are created as instances from the Matrix class::
649 >>> from sympy import Matrix
650 >>> Matrix([[1,0], [0,1]])
654 you can also put Symbols in it::
658 >>> A = Matrix([[1,x], [y,1]])
659 >>> A #doctest: +NORMALIZE_WHITESPACE
663 >>> A**2 #doctest: +NORMALIZE_WHITESPACE
670 For more information an examples with Matrices, see the LinearAlgebraTutorial.
672 .. index:: pattern matching, match, Wild, WildFunction
677 Use the ``.match()`` method, along with the ``Wild`` class, to perform pattern
678 matching on expressions. The method will return a dictionary with the required
679 substitutions, as follows::
681 >>> from sympy import *
685 >>> (5*x**2 + 3*x).match(p*x**2 + q*x)
688 >>> (x**2).match(p*x**q)
691 If the match is unsuccessful, it returns ``None``::
693 >>> print (x+1).match(p**x)
696 One can also make use of the `WildFunction` class to perform
697 more specific matches with functions and their arguments::
699 >>> f = WildFunction('f', nofargs=1)
700 >>> (5*cos(x)).match(p*f)
702 >>> (cos(3*x)).match(f(p*x))
704 >>> g = WildFunction('g', nofargs=2)
705 >>> (5*cos(x)).match(p*g)
708 One can also use the exclude parameter of the ``Wild`` class to ensure that
709 certain things do not show up in the result::
712 >>> p = Wild('p', exclude=[1,x])
713 >>> print (x+1).match(x+p) # 1 is excluded
715 >>> print (x+1).match(p+1) # x is excluded
717 >>> print (x+1).match(x+2+p) # -1 is not excluded
720 .. _printing-tutorial:
725 There are many ways how expressions can be printed.
729 This is what ``str(expression)`` returns and it looks like this:
731 >>> from sympy import Integral
732 >>> from sympy.abc import x
737 >>> print Integral(x**2, x)
744 This is a nice ascii-art printing produced by a ``pprint`` function:
746 >>> from sympy import Integral, pprint
747 >>> from sympy.abc import x
755 >>> pprint(Integral(x**2, x))
762 See also the wiki `Pretty Printing
763 <http://wiki.sympy.org/wiki/Pretty_Printing>`_ for more examples of a nice
766 Tip: To make the pretty printing default in the python interpreter, use::
769 Python 2.5.2 (r252:60911, Jun 25 2008, 17:58:32)
770 [GCC 4.3.1] on linux2
771 Type "help", "copyright", "credits" or "license" for more information.
772 >>> from sympy import *
774 >>> sys.displayhook = pprint
782 >>> Integral(x**2, x)
792 >>> from sympy.printing.python import print_python
793 >>> from sympy import Integral
794 >>> from sympy.abc import x
795 >>> print_python(x**2)
798 >>> print_python(1/x)
801 >>> print_python(Integral(x**2, x))
803 e = Integral(x**2, x)
808 >>> from sympy import Integral, latex
809 >>> from sympy.abc import x
814 >>> latex(Integral(x**2, x))
815 '$\\int {x}^{2}\\,dx$'
822 >>> from sympy.printing.mathml import print_mathml
823 >>> from sympy import Integral, latex
824 >>> from sympy.abc import x
825 >>> print_mathml(x**2)
836 >>> print_mathml(1/x)
851 >>> from sympy import Integral, pngview
852 >>> from sympy.abc import x
853 >>> pngview(Integral(x**2, x))
855 And a pyglet window with the LaTeX rendered expression will popup:
857 .. image:: pics/pngview1.png
862 ``isympy`` calls ``pprint`` automatically, so that's why you see pretty
865 Note that there is also a printing module available, ``sympy.printing``. Other
866 printing methods available trough this module are:
868 * ``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.
870 * ``latex(expr)``, ``print_latex(expr)``: Return or print, respectively, a `LaTeX <http://www.latex-project.org/>`_ representation of ``expr``
872 * ``mathml(expr)``, ``print_mathml(expr)``: Return or print, respectively, a `MathML <http://www.w3.org/Math/>`_ representation of ``expr``.
874 * ``print_gtk(expr)``: Print ``expr`` to `Gtkmathview <http://helm.cs.unibo.it/mml-widget/>`_, a GTK widget that displays MathML code. The `Gtkmathview <http://helm.cs.unibo.it/mml-widget/>`_ program is required.
876 Further documentation
877 =====================
879 Now it's time to learn more about SymPy. Go through the
880 :ref:`SymPy User's Guide <guide>` and
881 :ref:`SymPy Modules Reference <module-docs>`.
883 Be sure to also browse our public `wiki.sympy.org <http://wiki.sympy.org/>`_,
884 that contains a lot of useful examples, tutorials, cookbooks that we and our
885 users contributed and we encourage you to edit it.