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

Mathematical Functions

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

S = sympy.sqrt(X)
S
phi = sympy.cos(X)**2 + sympy.sin(X)**2
phi
# But not ...

np.sin(S)
# and not ...

math.sin(S)

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()
S.subs(X, 8)
S.subs(X, -8)
np.sqrt(-8)

Differentiation / Integration

Ds = S.diff(X)
Ds
Ds.integrate(X)
Ds.integrate((X,2,3))