Getting started with sympy

The package sympy adds symbolic mathematical manipulation to the python ecosystem. Like other computational algebra packages, it allows you to write expressions, simplify them, differentiate them and make substitutions. Sympy is relatively lightweight and is completely open source so it is quite an attractive starting point if you need to do some straightforward manipulations.

It is possible to have sympy automatically generate code that you can include in other programs and, if you are very ambitious, you can build in sympy as a library into your own code !

The documentation for sympy does assume some familiarity with computational algebra packages, you can find it here https://docs.sympy.org/latest/index.html.

This is a quick summary of some things that a symbolic algebra module can give you

import sympy
import math
import numpy as np

Symbols

Symbols are the building blocks of expressions and are defined like this

from sympy.core.symbol import Symbol

X = Symbol('x')
Y = Symbol('y')
psi = Symbol('\psi')

X + Y + psi
\[\displaystyle \psi + x + y\]

Mathematical Functions

Symbols can be built into expressions using a collection of (the usual) mathematical functions and operators

S = sympy.sqrt(X)
S
\[\displaystyle \sqrt{x}\]
phi = sympy.cos(X)**2 + sympy.sin(X)**2
phi
\[\displaystyle \sin^{2}{\left(x \right)} + \cos^{2}{\left(x \right)}\]
# But not ...

np.sin(S)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Pow' object has no attribute 'sin'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-fda2f851422a> in <module>
      1 # But not ...
      2 
----> 3 np.sin(S)

TypeError: loop of ufunc does not support argument 0 of type Pow which has no callable sin method
# and not ...

math.sin(S)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-cfc8d2947598> in <module>
      1 # and not ...
      2 
----> 3 math.sin(S)

/usr/share/miniconda3/envs/jupyter-book/lib/python3.7/site-packages/sympy/core/expr.py in __float__(self)
    325         if result.is_number and result.as_real_imag()[1]:
    326             raise TypeError("can't convert complex to float")
--> 327         raise TypeError("can't convert expression to float")
    328 
    329     def __complex__(self):

TypeError: can't convert expression to float

Simplification and Subsitution

Since we are working with abstract symbols, we can simplify expressions but we cannot, in general, evaluate them unless we subsitute values for the symbols:

phi.simplify()
\[\displaystyle 1\]
S.subs(X, 8)
\[\displaystyle 2 \sqrt{2}\]
S.subs(X, -8)
\[\displaystyle 2 \sqrt{2} i\]
np.sqrt(-8)
/usr/share/miniconda3/envs/jupyter-book/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
  """Entry point for launching an IPython kernel.
nan

Differentiation / Integration

Ds = S.diff(X)
Ds
\[\displaystyle \frac{1}{2 \sqrt{x}}\]
Ds.integrate(X)
\[\displaystyle \sqrt{x}\]
Ds.integrate((X,2,3))
\[\displaystyle - \sqrt{2} + \sqrt{3}\]