A Quick Guide to Symbolic Mathematics with SymPy
Learn how to manipulate mathematical expressions in Python
Overview of Your Journey
- Setting the Stage
- Installing SymPy
- Creating SymPy Symbols
- Solving Equations
- Useful Functions
- Other Things You Can do With SymPy
- Wrapping Up
1 โ Setting the Stage
Whether you are a student in university or working in data science, there is no way around mathematics. One might even say that data science is (simplistically put) a form of applied mathematics/statistics. In Python, there are many libraries that deal with mathematics numerically like NumPy, SciPy, Scikit-Learn, and Tensorflow. However, for dealing explicitly with mathematical symbols there is only one contender for the crown: SymPy.
SymPy stands for Symbolic Mathematics in Python and is a Python library for dealing with mathematics. It is one of the core libraries of the SciPy Ecosystem among other giants like NumPy, Pandas, and Matplotlib. With SymPy you can manipulate mathematical expressions. Moreover, you can solve university-level mathematical problems that require differentiation, integration, and linear algebra.
In this blog post, I will show you how to work with the basics in SymPy so that you can start to solve mathematical problems symbolically. Iโve previously made a video series on SymPy, so if you are more of a visual learner then feel free to check that out as well ๐
Prerequisites: You should probably know the basics of Python. Other than that, you donโt need any experience with SymPy ๐
2 โ Installing SymPy
The developers of SymPy recommend installing SymPy through Anaconda. If you are using Anaconda, then you should already have SymPy installed. To make sure you have the latest version, then run the following command in the Anaconda prompt:
conda update sympy
If you are not using Anaconda, but are using PIP then you can run the command:
pip install sympy
For other ways of installing SymPy, check out the Installation Options.
3 โ Creating SymPy Symbols
Now let us get started with SymPy! The basic object of SymPy is a symbol. To create a symbol x in SymPy you can write:
# Import the package sympy with the alias sp
import sympy as sp
# Create a symbol x
x = sp.symbols("x")
The code above creates the symbol x . Symbols in SymPy are meant to simulate mathematical symbols that represent unknown quantities. As such, the following calculation should come as no surprise:
print(x + 3*x)
Output: 4*x
As you can see from above, the symbol x works like an unknown quantity. If you want to create more than one symbol, then you can write as follows:
y, z = sp.symbols("y z")
Here you have made two symbols, y and z , at the same time. Now you can add, subtract, multiply, divide these symbols however you like:
print((3*x + 2*y - 3*z)/x)
Output: (3*x + 2*y - 3*z)/x
In the next section I will show you how to solve equations with SymPy ๐ฅ
Pro Tip: If you look at SymPyโs documentation, you will sometimes see that they use the import statement
from sympy import *. This is a bad idea outside of a quick test (and even there I would say it builds bad habits). The problem is that you can overwrite functions and classes from other packages by doing this. Therefore I always recommend to writeimport sympy as sp.
4 โ Solving Equations
Let us now use SymPy symbols to solve equations: Say that you have the second-degree polynomial x**2 + 5*x + 6 . How can you solve the equation x**2 + 5*x + 6 = 0 ? Most of us have some vague recollection of how to do this by hand, but how do you make SymPy do the job? The following code first creates a symbol x , then creates the equation in question, and then finally solves the equation:
import sympy as sp
# Creating the symbol x
x = sp.symbols("x")
# Creates the equation in question
equation = sp.Eq(x**2 + 5*x + 6, 0)
# Solving the equation
solution = sp.solveset(equation, x)
Let us look at the variable solution the code above created:
print(type(solution))
Output: <class 'sympy.sets.sets.FiniteSet'>
print(solution)
Output: FiniteSet(-3, -2)
As you can see, the solution variable gives us the two solutions to the equation x**2 + 5*x + 6 = 0 . SymPyโs FiniteSet type is an iterable, so you can loop through it if you like:
for num in solution:
print(num)
Output:
-3
-2
If you want to extract the numbers -3 and -2 from the solution variable you can e.g. first turn solution into a list, and then index as usual:
# Turn solution into a list
solution_list = list(solution)
# Access the individual solutions
print(solution_list[0])
Output: -3
We just went through a simple second-degree polynomial that you probably could have solved by hand if you bothered. However, SymPy is far better than you and me for solving equations (sorry not sorry). Try something harder yourself to see how much SymPy can handle ๐
5 โ Useful Functions
One neat thing about SymPy is that it is packed with useful mathematical functions. These functions can be used right out of the box, and you should get familiar with some of the most common ones.
The following script creates three different equations with functions from SymPy:
import sympy as sp
x = sp.symbols("x")
equation1 = sp.Eq(sp.cos(x) + 17*x, 0)
equation2 = sp.Eq(sp.exp(x ** 2) - 5*sp.log(x), 0)
equation3 = sp.Eq(sp.sinh(x) ** 2 + sp.cosh(x) ** 2, 0)
If you read the above code carefully, you will find
cos(the cosine function)sin(the sine function)exp(the exponential function)sinh(the hyperbolic sine function)cosh(the hyperbolic cosine function)
Equipped with these functions, you can e.g. make activation functions used for deep neural networks. For instance, the well-known sigmoid activation function can be written as follows:
sigmoid = 1/(1 + sp.exp(-x))
If you want to substitute values into the sigmoid function, you can use the .subs() method. Letโs try this:
print(sigmoid.subs(x, 2))
Output: 1/(exp(-2) + 1)
Hmm. While technically correct, it would be nice to have the value as a floating point number. To get this, you can use the function sp.N() (the N stands for Numeric):
print(sp.N(sigmoid.subs(x, 2)))
Output: 0.880797077977882
6 โ Other Things You Can Do With SymPy
Rather than rambling on about more topics in detail, let me give you a list of things that you can check out to improve your SymPy skills:
- Derivatives and Integrals: SymPy can do most things you would learn in an introductory calculus class (except the thinking ๐ ). You can start by checking our differentiation of functions in SymPy.
- Matricies and Linear Algebra: SymPy can work with matrices and do basic operation from linear algebra. The syntax is somewhat similar to the syntax used by NumPy, but there are also differences. To get started, check out matricies in Sympy
- Simplifications: SymPy is clever enough to do some simplifications to expressions automatically. However, if you want more fine-tuned control over this, then check out simplifications in SymPy.
- Deep Dive into SymPy: Under the hood, SymPy uses a tree-based structure to keep track of expressions known as an expression tree. If you want to deep into the inner workings of SymPy, the check out expression trees.
- Relationship with NumPy: NumPy and SymPy are both libraries that can deal with mathematics. However, they are fundamentally different! NumPy operates numerically, while SymPy works with symbolic expressions. There are both advantages and disadvantages to both approaches. Luckily, there is a clever way of "exporting" a SymPy expression to a NumPy array. Check out the lambdify function in SymPy for how this works.
7 โ Wrapping Up
If you need to learn more about SymPy, then check out the SymPy documentation or my video series on SymPy.
Like my writing? Check out my blog posts Type Hints, Underscores in Python, 5 Awesome NumPy Functions, and 5 Dictionary Tips for more Python content. If you are interested in data science, programming, or anything in between, then feel free to add me on LinkedIn and say hi โ
Share This Article
Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
Write for TDS