What's new? | Help | Directory | Sign in
Google
sympy
Python library for symbolic mathematics
  
  
  
  
    
Search
for
Updated Apr 01, 2008 by ondrej.certik
Tutorial  
First steps with sympy

This used to be the old Tutorial for SymPy, but now we manage all our docs at http://docs.sympy.org/, so the new Tutorial is here:

http://docs.sympy.org/tutorial.html

This old page will be left here for some time if you were used to it.

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

    >>> from sympy import *

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.

    >>> from sympy import *
    >>> a = Rational(1,2)

    >>> a
    1/2

    >>> a*2
    1

    >>> Rational(2)**50/Rational(10)**50
    1/88817841970012523233890533447265625

proceed with caution while working with python int's since they truncate integer division, and that's why:

   >>> 1/2
   0

   >>> 1.0/2
   0.5

You can however do:

  >>> from __future__ import division

  >>> 1/2 #doctest: +SKIP 
  0.5

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 precission:

    >>> pi**2
    pi**2

    >>> pi.evalf()
    3.141592653589793238462643383

    >>> (pi+exp(1)).evalf()
    5.859874482049203234066343309

as you see, evalf evaluates the expression to a floating-point number

There is also a class representing mathematical infinity, called oo:

    >>> oo > 99999
    True
    >>> oo + 1
    oo

Symbols

In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly:

    >>> from sympy import *
    >>> x = Symbol('x')
    >>> y = Symbol('y')

Then you can play with them:

    >>> x+y+x-y
    2*x

    >>> (x+y)**2
    (x+y)**2

    >>> ((x+y)**2).expand()
    2*x*y+x**2+y**2

And substitute them for other symbols or numbers using subs(var, substitution):

    >>> ((x+y)**2).subs(x, 1)
    (1+y)**2

    >>> ((x+y)**2).subs(x, y)
    4*y**2

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)

   >>> from sympy import *
   >>> x=Symbol("x")
   >>> limit(sin(x)/x, x, 0)
   1

you can also calculate the limit at infinity:

   >>> 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

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:

    >>> 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)

You can check, that it is correct by:

    >>> limit((tan(x+y)-tan(x))/y, y, 0)
    cos(x)**(-2)

Higher derivatives can be calculated using the diff(func, var, n) method:

    >>> 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)

Series expansion

Use .series(var, order):

>>> from sympy import *
>>> x = Symbol('x')
>>> cos(x).series(x, 0, 10)
1 - 1/2*x**2 - 1/720*x**6 + (1/24)*x**4 + (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)

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.

>>> from sympy import *
>>> x, y = symbols('xy')

You can integrate elementary functions:

>>> 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)

Also special functions are handled easily:

>>> integrate(exp(-x**2)*erf(x), x)
(1/4)*pi**(1/2)*erf(x)**2

It is possible to compute definite integral:

>>> integrate(x**3, (x, -1, 1))
0
>>> integrate(sin(x), (x, 0, pi/2))
1
>>> integrate(cos(x), (x, -pi/2, pi/2))
2

Also improper integrals are supported as well:

>>> integrate(exp(-x), (x, 0, oo))
1
>>> integrate(log(x), (x, 0, 1))
-1

Complex numbers

>>> 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)

Differential Equations

In isympy:

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)

Algebraic equations

In isympy:

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}

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:

    >>> from sympy import *
    >>> from sympy.matrices import Matrix
    >>> Matrix([[1,0], [0,1]]) #doctest: +NORMALIZE_WHITESPACE 
    1 0 
    0 1
 

you can also put Symbols in it:

    >>> x = Symbol('x')
    >>> y = Symbol('y')
    >>> A = Matrix([[1,x], [y,1]])
    >>> A #doctest: +NORMALIZE_WHITESPACE
    1 x 
    y 1
 
    >>> A**2 #doctest: +NORMALIZE_WHITESPACE
    1+x*y 2*x 
    2*y 1+x*y 
 
    >>> 1
    1

For more information an examples with Matrices, see the LinearAlgebraTutorial

Pattern matching

Use the .match() method (available in 0.4), along with the Wild class (available in 0.5), to perform pattern matching on expressions. The method will return a dictionary with the required substitutions, as follows:

    >>> 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}

If the match is unsuccessful, it returns None:

    >>> print (x+1).match(p**x)
    None

One can also make use of the WildFunction class (available in 0.5) to perform more specific matches with functions and their arguments:

    >>> 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

One can also use the exclude parameter of the Wild class to ensure that certain things do not show up in the result:

    >>> 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}

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:

>>> 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

>>> 

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:

Modules

The following list provides links to documentation for some of the various modules SymPy offers

Be sure to also browse the wiki.sympy.org, that contains a lot of useful examples, tutorials, cookbooks that we and our users contributed and we encourage you to edit it.


Comment by gidesa, Dec 27, 2007

Cool! I Think it's the best package in the world!

Comment by okoks9...@naver.com, Dec 28, 2007

It's nice!

Comment by smp1...@163.com, Jan 03, 2008

very good! Can it compute the integrate of function, like f(x,y,z)?

Comment by ondrej.certik, Jan 04, 2008

Yes, it can. Please ask on the mailinglist with any problems.

Comment by 1001night, Jan 16, 2008

Great work! Anyone who caluate with algebra formula everyday would catch the value of this project.With this and the SciPy? module, the softwares such as "Mathematic","Matlab","Maple" and so on, are not necessary once more. Bless you!

Comment by cafeeee, Jan 16, 2008

Great!

Comment by hoxide, Feb 21, 2008

How to simplify sin(t)+cos(t) to 1?

Comment by mensana...@aol.com, Mar 01, 2008

You need to fix this:

>>> help(sympy.S)

Traceback (most recent call last):

File "<pyshell#0>", line 1, in <module>
help(sympy.S)
File "C:\Python25\lib\site.py", line 346, in call
return pydoc.help(args, kwds)
File "C:\Python25\lib\pydoc.py", line 1642, in call
self.help(request)
File "C:\Python25\lib\pydoc.py", line 1686, in help
else: doc(request, 'Help on %s:')
File "C:\Python25\lib\pydoc.py", line 1464, in doc
object, name = resolve(thing, forceload)
File "C:\Python25\lib\pydoc.py", line 1459, in resolve
return thing, getattr(thing, 'name', None)
File "C:\Python25\Lib\site-packages\sympy\core\basic.py", line 1169, in getattr
assert issubclass(cls, Singleton),cls
TypeError?: issubclass() arg 1 must be a class

Comment by ondrej.certik, Mar 21, 2008

This works for me. Please use issues for reporting bugs.

Comment by alsuren, May 04, 2008

what I think hoxide means is sin(x)2 + cos(x)2 === 1 To do this automatically, try: In 19?: trigsimp(sin(x)2+cos(x)2) Out19?: 1


Sign in to add a comment