Sympy: Symbolic Mathematics In Python For Engineers, Students, and Researchers

Halis Manaz
5 min readNov 29, 2022

--

What Is Sympy?

Sympy is an open-source Python library for symbolic mathematics. When you read the previous sentence, the question may come to mind: so what is this symbolic mathematics? In symbolic maths, computers deal with mathematical equations, expressions, and formulas in symbolic form to calculate and manipulate. Symbolic mathematics focus on variables in any equation instead of numeric values.

Why Should It Be Used?

Readability In Math

If your operations or equations are getting more and more complex, it is hard to deal with them. Because equations in standard Python math are not human readable. These are suitable for computers. This situation becomes an error-prone situation for people. However thanks to Sympy, complex equations are converted to human-readable format.

Precision

In math, some calculations cannot be represented by a finite decimal, because it is irrational numbers. For example, the square root of thirty-two is an example of an irrational number. You can not compute the exact value of the square root of thirty-two with decimal precision. In symbolic math, irrational numbers are left unevaluated to become more precise and readable.

Variable Base Computation

Like indefinite integral or simplification on formula, some calculations are based on variables instead of numbers. The output should be in variable form, not the exact value. You can not do this with standard Python. However, Sympy could do this. You can even easily calculate the exact result by assigning values to the variables in the result.

Basics

Installing and Importing

First of all, you should install Sympy libraries. You can use conda environment or pip. Type the following code into your terminal to install the library

pip install sympy

After installing the library, you should import Sympy. In this article, I will use the Sympy library with the abbreviation sp

import sympy as sp

Creating Symbols and Equations

You can create symbols with sp.symbols functions. Also, you can create multiple symbols at the same time.

x, y, z = sp.symbols('x y z')

Additionally, you can use infinity symbols with sp.oo

infinity_symbol = sp.oo

After creating symbols, you can easily create your equation like writing standard Python equations. Furthermore, you can use trigonometric and exponential functions thanks to Sympy

You can factor the equations you write on a variable basis or write them in full format with expand function.

Plot

Thanks to Sympy, you can plot your equations easily. Sympy uses the matplotlib library for visualizing equations. Therefore, if you are familiar with matplotlib, you can use it easily. In addition, you can plot multiple

plot1 = sp.plot(sp.sin(x), show=False, legend=True)
plot2 = sp.plot(-sp.sin(x), show=False)

plot1.append(plot2[0])

plot1.show()

Solve

You can find the roots of your equations with sp.solve function. sp.solve function returns a list of roots of the equation that you want to solve. You can convert root value to float or integer value if it is not complex root

Calculus

You can calculate all calculus operations with Sympy. Moreover, you can combine these with each other for complex processes. Let’s start with derivative calculation. You can see below, you can calculate the derivative of the equation.

You can also calculate the integral of equations. If you need the exact value of the integral. You can calculate the exact value with the boundaries of the integral.

The limit calculation is also available in the Sympy library

Matrix

You can calculate matrix operations with Sympy. In addition, you can convert your matrixes to NumPy array for further calculations. For matrixes, there are more complex functions. You can look at there

Example

Let’s make a small example. There are two equations. One of them is y=x and the other one is y=10sin(x) equation. We will find the intersection points of these equations, the first derivative points of 10sin(x) and the second derivative points of 10sin(x).

Let’s start with import

import sympy as sp
import matplotlib.pyplot as plt
import numpy as np

After importing libraries, create x symbols, and after that create equations.

x = sp.symbols('x')
eq1 = 10*sp.sin(x)
eq2 = x

In this example, our range is between -10 and +10. Therefore, find the intersection points between -10 and +10.

intersection_points = {sp.nsolve(eq1-eq2, x) for x in range(-10, 10)}

After that, create an array with linspace and find the y values of equations.

x_vals = np.linspace(-10, 10, 1000)
y_vals_sin_x = sp.lambdify(x, [eq1])(x_vals)
y_vals_x = sp.lambdify(x, [eq2])(x_vals)

Calculate the first and second derivative points of the 10sin(x) equation with the solveset function

first_derivative = list(sp.solveset(sp.diff(eq1), x, sp.Interval(-10, 10)))
first_derivativeY = [eq1.subs(x, a) for a in first_derivative]
second_derivative = list(sp.solveset(sp.diff(eq1, x, 2), x, sp.Interval(-10, 10)))
second_derivativeY = [eq1.subs(x, a) for a in second_derivative]

Plot them all with matplotlib

plt.plot(x_vals, np.transpose(y_vals_sin_x), label='10sin(x)', color='blue')
plt.plot(x_vals,np.transpose(y_vals_x), label='x', color='purple')
plt.plot(list(intersection_points), list(intersection_points), 'o', color='red', label='Intersection Points')
plt.plot(first_derivative, first_derivativeY, 'o', color='green', label='First Derivative Points of 10sin(x)')
plt.plot(second_derivative, second_derivativeY, 'o', color='orange', label='Second Derivative Points of 10sin(x)')

Adjust plot settings like title, gridlines, etc.

plt.title('y=10sin(x) and y=x Graph')
plt.grid(which='both')
plt.legend(bbox_to_anchor=(1.05, 0.35))
plt.show()

End result!

Conclusion

I discovered the sympy library 2 months before I graduated from engineering. After discovering it, there was a library that I wish I had learned much earlier. If you are a student or a researcher in engineering, physics, mathematics, etc., Sympy will definitely make your job easier. It can easily solve even the most complex equations and matrices. You can easily visualize them and print your results in latex format for human readability. I recommend you take a look. You can reach the source code from here

Thanks For Reading, Follow Me For More

Previous Article

--

--

Halis Manaz

Hi, I am Halis. I am interested in Python, data analysis, and machine learning. I share what I learned, what I found interesting, and my portfolio projects