Symbolic Math with SymPy

This article shows how to solve math equations and expressions symbolically, in Python. Thanks to the Sympy library, this turns out to be an extremely easy task.

However, as you will see in the following examples, the number of tools and functions provided by this library is huge. Thanks to all its features, Sympy represents a really powerful algebra system with which we can solve in a very immediate way, mathematical expressions, equations, inequalities and even systems of equations/inequalities.

For these reasons, Sympy represents a fundamental tool for solving a plethora of math related problems. The article is divided into different sections, each of which deals with a specific Sympy function. If you are interested in the topic, you can find the documentation about all the herein described functions (and lots of others) at https://www.sympy.org/en/index.html

Importing Sympy

The first step involves importing into our script the Simpy library; since multiple different packages will be used throughout this example, we import them all by writing the following code line (to import Sympy you must have previously installed it, if you have not done it yet, type “pip install sympy” in your terminal).

from sympy import *

Defining variables and functions

We start by defining the variables that we want to use in our calculations. To do this, we exploit the Sympy function symbols() which takes as input a string and turns it into a Sympy variable; we then assign the value of the function to a variable with the same name of the chosen string. In the following code lines, we initialize two variables “x” and “y”.

# Initializing two variables
x = symbols('x')  
y = symbols('y')

A similar procedure can be employed to define the name of the functions that will be used in the script; this time, the Sympy function that serves to the purpose is Function() and works in the same way as symbols(). We hence initialize a function called “f”, from this moment, every time we type “f” on the script, we are referring to a function.

# Initializing a function f
f = Function('f')

Using Sympy in your computer terminal

Sympy can be even used directly from your terminal; it is here that its capability of symbolically solve mathematical equations and functions expresses its best. We will now see how to initialize and directly use Sympy in the terminal. The first thing to do, is to open your terminal and import Sympy in a similar way as did before. We hence type “import sympy” and press enter. After this, we enter the following command “sympy.init_session()”, the following lines contain the two just described commands and the output that is prompted by your terminal.

>>> import sympy
>>> sympy.init_session()
Python console for SymPy 1.7.1 (Python 3.7.1-64-bit) (ground types: python)
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()  

As you can see, after the sympy.init_session() command, multiple Sympy packages were imported; moreover, the letters “x”, “y”, “z” and “t” were initialized as Sympy variables, “k”, “m” and “n” as integer parameters, while the letters “f”, “g” and “h” as functions.

All these tasks were executed automatically within the sympy.init_session() command, which basically initiated a Sympy session with some pre-defined functions and variables.

The advantage of using the terminal over the text editor is that it will prompt all the functions and equations using an improved graphical style, making them (as we will see) more immediate. Most of the commands that will follow in the next sections, can be typed both in the script and in the terminal, I will specify when some specific functions will not work on one of the two platforms.

Expanding and simplifying mathematical expressions

In this section we will learn how to use Sympy to expand or simplify a mathematical expression. Both the tasks can be done automatically and instantaneously by just exploiting the functions expand() and factor().

To see how the expand() function works, we first define a function f = (3x + 5y2 – 6)2 and then we pass it as the only input parameter of the function expand(). The following lines are typed within the terminal in order to obtain a better graphical output; however, they work in the very same way when typed within the script.

>>> f = (3*x +5*y - 6)**2
>>> expand(f)
     2                       2
9⋅x  + 30⋅x⋅y - 36⋅x + 25⋅y  - 60⋅y + 36

As you can see from the reported results, the function expand() has calculated the expression defined within the function f and printed it in an improved graphical way, avoiding the asterisks and placing the exponents as apices. The presenting style may vary among different terminals, but it generally improves with respect to the input one.

On the other hand, the function factor() works in the exact opposite way, it simplify the expression that is passed within its brackets. You can see an example in the following lines.

>>> g = x**3 + y**3 + 3*x*y**2 + 3*x**2*y
>>> factor(g)

Solving equations and inequalities

Another useful feature offered by Sympy is the possibility to find the solution to algebraic equations by exploiting the function .solve().

This function takes as input two different parameters, the equation that we want to solve and the variable for which we want to solve it, respectively.

This is particularly useful in the case of symbolic solutions of equations with multiple variables in which we might be interested in obtaining the symbolic solution with respect to one of the two unknowns. The following lines report either the numerical solution of a one-variable equation and the symbolic solution of a two-variables equation with respect to the variable “y”.

>>> solve(2*x + 3)
[-3/2]
>>> solve(2*x + 3 -y, y)
[2⋅x + 3] 

In a similar way we can also obtain the numerical and/or symbolical solution of higher order equation or inequalities. Both the tasks are displayed in the following lines.

>>> solve(x**3 - 7*x)
[0, -√7, √7]
>>> solve(x +4*y -7 > 0, y)
      7    x
y > ─ - ─
      4    4

Solving systems of equations/inequalities

Sympy can be used to solve systems of equations/inequalities as well. For doing this, we will exploit, again, the function solve(). In the case of a system of equations, we enter the equations as elements of a list; the following lines describes the solution of a system of three linear equations by using solve().

>>> solve([x + 2*y - 5*z, z + 3 - x,  y + x + z])
{x: 21/8, y: -9/4, z: -3/8} 

As can be seen, the output of the solve() function are the values of the three different system variables. In the same way, we can also obtain the solution of systems of inequalities; it is sufficient to enter the inequalities as elements of a list; this time the “>” “<” symbols have to be specified for both the inequalities.

>>> solve([x**2 + 2*x > 2, 4*x + 5 < 6])
-∞ < x ∧ x < -√3 - 1

As usual, the solution is printed right under our command, exploiting Boolean symbols for the operator “and”, “or”.

Conclusion

This article presented some of the basic functions provided by the Sympy library. In particular, we saw how to exploit Sympy to define variables and functions; how to symbolically expand and simplify mathematical expressions and how to use this library for solving equations, inequalities and even systems of equations/inequalities. The functions shown in the article can be typed both in the text of the script but also directly in the terminal (or Jupyter notebooks) in order to obtain an immediate evaluation and a better graphical representation of the performed calculations.