# Sympy - Symbolic algebra in Python

J.R. Johansson (robert@riken.jp) http://dml.riken.jp/~rob/

The latest version of this IPython notebook lecture is available at http://github.com/jrjohansson/scientific-python-lectures.

The other notebooks in this lecture series are indexed at http://jrjohansson.github.com.

Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline].


## Introduction

There are two notable Computer Algebra Systems (CAS) for Python:

• SymPy - A python module that can be used in any Python program, or in an IPython session, that provides powerful CAS features.
• Sage - Sage is a full-featured and very powerful CAS enviroment that aims to provide an open source system that competes with Mathematica and Maple. Sage is not a regular Python module, but rather a CAS environment that uses Python as its programming language.

Sage is in some aspects more powerful than SymPy, but both offer very comprehensive CAS functionality. The advantage of SymPy is that it is a regular Python module and integrates well with the IPython notebook.

In this lecture we will therefore look at how to use SymPy with IPython notebooks. If you are interested in an open source CAS environment I also recommend to read more about Sage.

To get started using SymPy in a Python program or notebook, import the module sympy:

To get nice-looking $\LaTeX$ formatted output run:

## Symbolic variables

In SymPy we need to create symbols for the variables we want to work with. We can create a new symbol using the Symbol class:

sympy.core.symbol.Symbol


We can add assumptions to symbols when we create them:

### Complex numbers

The imaginary unit is denoted I in Sympy.

### Rational numbers

There are three different numerical types in SymPy: Real, Rational, Integer:

## Numerical evaluation

SymPy uses a library for artitrary precision as numerical backend, and has predefined SymPy expressions for a number of mathematical constants, such as: pi, e, oo for infinity.

To evaluate an expression numerically we can use the evalf function (or N). It takes an argument n which specifies the number of significant digits.

When we numerically evaluate algebraic expressions we often want to substitute a symbol with a numerical value. In SymPy we do that using the subs function:

The subs function can of course also be used to substitute Symbols and expressions:

We can also combine numerical evolution of expressions with NumPy arrays:

However, this kind of numerical evolution can be very slow, and there is a much more efficient way to do it: Use the function lambdify to “compile” a Sympy expression into a function that is much more efficient to evaluate numerically:

The speedup when using “lambdified” functions instead of direct numerical evaluation can be significant, often several orders of magnitude. Even in this simple example we get a significant speed up:

10 loops, best of 3: 20.4 ms per loop

100000 loops, best of 3: 3.67 µs per loop


## Algebraic manipulations

One of the main uses of an CAS is to perform algebraic manipulations of expressions. For example, we might want to expand a product, factor an expression, or simply an expression. The functions for doing these basic operations in SymPy are demonstrated in this section.

### Expand and factor

The first steps in an algebraic manipulation

The expand function takes a number of keywords arguments which we can tell the functions what kind of expansions we want to have performed. For example, to expand trigonometric expressions, use the trig=True keyword argument:

See help(expand) for a detailed explanation of the various types of expansions the expand functions can perform.

The opposite a product expansion is of course factoring. The factor an expression in SymPy use the factor function:

### Simplify

The simplify tries to simplify an expression into a nice looking expression, using various techniques. More specific alternatives to the simplify functions also exists: trigsimp, powsimp, logcombine, etc.

The basic usages of these functions are as follows:

### apart and together

To manipulate symbolic expressions of fractions, we can use the apart and together functions:

Simplify usually combines fractions but does not factor:

## Calculus

In addition to algebraic manipulations, the other main use of CAS is to do calculus, like derivatives and integrals of algebraic expressions.

### Differentiation

Differentiation is usually simple. Use the diff function. The first argument is the expression to take the derivative of, and the second argument is the symbol by which to take the derivative:

For higher order derivatives we can do:

To calculate the derivative of a multivariate expression, we can do:

$\frac{d^3f}{dxdy^2}$

## Integration

Integration is done in a similar fashion:

By providing limits for the integration variable we can evaluate definite integrals:

and also improper integrals

Remember, oo is the SymPy notation for inifinity.

### Sums and products

We can evaluate sums and products using the functions: ‘Sum’

Products work much the same way:

## Limits

Limits can be evaluated using the limit function. For example,

We can use ‘limit’ to check the result of derivation using the diff function:

$\displaystyle \frac{\mathrm{d}f(x,y)}{\mathrm{d}x} = \frac{f(x+h,y)-f(x,y)}{h}$

OK!

We can change the direction from which we approach the limiting point using the dir keywork argument:

## Series

Series expansion is also one of the most useful features of a CAS. In SymPy we can perform a series expansion of an expression using the series function:

By default it expands the expression around $x=0$, but we can expand around any value of $x$ by explicitly include a value in the function call:

And we can explicitly define to which order the series expansion should be carried out:

The series expansion includes the order of the approximation, which is very useful for keeping track of the order of validity when we do calculations with series expansions of different order:

If we want to get rid of the order information we can use the removeO method:

But note that this is not the correct expansion of $\cos(x)\sin(x)$ to $5$th order:

## Linear algebra

### Matrices

Matrices are defined using the Matrix class:

With Matrix class instances we can do the usual matrix algebra operations:

And calculate determinants and inverses, and the like:

## Solving equations

For solving equations and systems of equations we can use the solve function:

System of equations:

In terms of other symbolic expressions:

## Quantum mechanics: noncommuting variables

How about non-commuting symbols? In quantum mechanics we need to work with noncommuting operators, and SymPy has a nice support for noncommuting symbols and even a subpackage for quantum mechanics related calculations!

## States

We can define symbol states, kets and bras:

Use qapply to distribute a mutiplication:

### Operators

Check if they are commuting!

We can use the doit method to evaluate the commutator:

We can mix quantum operators with C-numbers:

To expand the commutator, use the expand method with the commutator=True keyword argument:

Let’s look at the commutator of the electromagnetic field quadatures $x$ and $p$. We can write the quadrature operators in terms of the creation and annihilation operators as:

$\displaystyle x = (a + a^\dagger)/\sqrt{2}$

$\displaystyle p = -i(a - a^\dagger)/\sqrt{2}$

Let’s expand the commutator $[x,p]$

Here we see directly that the well known commutation relation for the quadratures

$[x,p]=i$

is a directly related to

$[A, A^\dagger]=1$

(which SymPy does not know about, and does not simplify).

For more details on the quantum module in SymPy, see:

• http://docs.sympy.org/0.7.2/modules/physics/quantum/index.html
• http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/master/docs/examples/notebooks/sympy_quantum_computing.ipynb

• http://sympy.org/en/index.html - The SymPy projects web page.
• https://github.com/sympy/sympy - The source code of SymPy.
• http://live.sympy.org - Online version of SymPy for testing and demonstrations.

## Versions

SoftwareVersion
Python3.3.2+ (default, Feb 28 2014, 00:52:16) [GCC 4.8.1]
IPython2.2.0
OSposix [linux]
numpy1.8.2
sympy0.7.5
Tue Aug 26 22:57:37 2014 JST

Tags:

Categories:

Updated: