Navigation

Term rewriting is a very general class of functionalities which are used to
convert expressions of one type in terms of expressions of different kind. For
example expanding, combining and converting expressions apply to term
rewriting, and also simplification routines can be included here. Currently
SymPy has several functions and basic built-in methods for performing various
types of rewriting.

The simplest rewrite rule is expanding expressions into a _sparse_ form.
Expanding has several flavors and include expanding complex valued expressions,
arithmetic expand of products and powers but also expanding functions in terms
of more general functions is possible. Below are listed all currently available
expand rules.

Arithmetic expand is done by default in expand() so the keyword basic can
be omitted. However you can set basic=False to avoid this type of expand if
you use rules described below. This give complete control on what is done with
the expression.

Another type of expand rule is expanding complex valued expressions and putting
them into a normal form. For this complex keyword is used. Note that it will
always perform arithmetic expand to obtain the desired normal form:

Note also that the same behavior can be obtained by using as_real_imag()
method. However it will return a tuple containing the real part in the first
place and the imaginary part in the other. This can be also done in a two step
process by using collect function:

There is also possibility for expanding expressions in terms of expressions of
different kind. This is very general type of expanding and usually you would
use rewrite() to do specific type of rewrite:

Optimizations to be performed before and after common subexpressions
elimination can be passed in the``optimizations`` optional argument. A set of
predefined basic optimizations can be applied by passing
optimizations='basic':

However, these optimizations can be very slow for large expressions. Moreover,
if speed is a concern, one can pass the option order='none'. Order of
terms will then be dependent on hashing algorithm implementation, but speed
will be greatly improved.