When it comes to Mathematics and Computing, the Python SymPy library has every feature you possibly need. Whether it’s something as simple as creating mathematical expressions, or performing differentiation and integration, SymPy can do it all.
What we will be focusing on in this specific SymPy tutorial, is how to create Mathematical expressions, and perform various operations on them. Some of the operations that we will be discussing today include factorization, simplification and expansion.
Mathematical Expressions with SymPy
SymPy gives us the ability to create actual expressions using variables (called symbols in SymPy). For example, if you want to represent the equation 2x2 + 4x + 5
in Python, how would you do so? You could represent such an equation in a string, but it would be of little use without SymPy.
So how do we create a SymPy-compatible expression? Well it’s pretty straightforward. First we need to define a symbol, which represents an unknown/variable like “x” or “y”.
from sympy import symbols
x, y = symbols("x y")
We can now use the x
and y
symbols to construct expressions. No need to make a string or anything, just do it normally by treating them like integers. Now let’s try and create a bunch of different expressions to see how it works.
from sympy import symbols
x, y = symbols("x y")
expr1 = 2*x + 4*y # 2x + 2y
expr2 = 2*(x**2) + 5 # 2(x^2) + 5
expr3 = x**2 + y**2 # x^2 + y^2
Modifying Expressions in SymPy
Now that we know how to create expressions, let’s take a look at the various operations we can apply on them!
Here we will try adding some constants and other symbols to the expressions. Let’s see what kind of effect it has.
print(expr1)
expr1 += 5
print(expr1)
2*x + 4*y
2*x + 4*y + 5
As you can see, the expression was actually modified. This makes calculations and mathematical computation very easy.
SymPy will even automatically adjust the expressions as you modify it. For example, if you have an expression "2x"
, and you add "x"
to it, you might expect it to just concatenate and become 2x + x
. But nope, SymPy will automatically simplify it to 3x
.
Here’s a code snippet illustrating this feature.
expr = 2*y + x + 5
print(expr)
expr -= x
print(expr)
expr += 3
print(expr)
x + 2*y + 5
2*y + 5
2*y + 8
Solving Expressions in SymPy
What’s even cooler, is that SymPy can literally solve entire equations for you, and return the root(s). No need to code the entire thing yourself, just use a single function along with the SymPy expression and a list of root(s) will be returned.
Let’s try to use the SymPy solve()
on the expression x2 - x - 6
.
import sympy
from sympy import symbols
x, y = symbols("x y")
expr = x**2 - x - 6
print(sympy.solve(expr))
[-2, 3]
Let’s try this out on another expression.
expr = (x + 1)*(x - 1)*(x + 5)
print(sympy.expand(expr))
print(sympy.solve(expr))
x**3 + 5*x**2 - x - 5
[-5, -1, 1]
What is this expand()
function? Keep reading to find out!
In the next section, we will cover several such operations, and explain how you can use them in your SymPy code.
Substituting Values in Sympy Expressions
Now that we know how to create and modify expressions in SymPy, let’s take a look at how to evaluate them. What we need to do here, is use the subs()
method to substitute the symbols with numerical values.
expr1 = 2*(x**2) + 5 # 2(x^2) + 5
print("Expr 1: (x=2) ", expr1.subs(x, 2))
Expr 1: (x=2) 13
After substituting the value “2” in the above expression, we got the value 13.
Now let’s try this for an expression which has multiple unknowns.
expr2 = 2*x + 4*y # 2x + 2y
print("Expr 2: (x=2, y=4) ", expr2.subs( {x: 2, y: 4} ))
Expr 2: (x=2, y=4) 20
We can also substitute them with other symbols, if you wish to represent an expression in terms of another symbol.
x, y, a, b = symbols("x y a b")
expr3 = x**2 + y**2 # x^2 + y^2
print(expr3.subs({x: a, y: b}))
a**2 + b**2
Expanding Expressions in SymPy
SymPy by nature, will attempt to simplify expressions when performing operations on them. Let’s take a look at a small example.
from sympy import symbols, expand
x, y = symbols("x y")
expr = x + 5
print(expr * y)
y*(x + 5)
As you can see, the “y” is currently outside the brackets. SymPy offers us the option of expanding this expression by using the expand(). Let’s see what kind of effect it has!
from sympy import symbols, expand
x, y = symbols("x y")
expr = x + 5
print(expand(expr * y))
x*y + 5*y
Simplifying Expressions in SymPy
The reverse of expand()
, simplify is a function that attempts to find the simplest form of any expression. SymPy actually has many different functions for simplification, but simplify()
is the general version, that will attempt to apply each every possible function to obtain the simplest form.
Let’s take a look at an example or two.
from sympy import symbols, simplify, cos, sin
x, y = symbols("x y")
print( simplify(sin(x)**2 + cos(x)**2) )
print( simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1)) )
1
x - 1
A disadvantage of using simplify()
is that it can be a bit slow, since it tries various kinds of simplifications before picking the most suitable one. If you already know what kind of simplification is required, then it is better to apply that specific simplification function. For example, the trigsimp()
function for simplifying trigonometric identities.
Factorizing Expressions in SymPy
Many people tend to confuse the simplify()
function with the factor()
function, which is used to factorize expressions. The simplify function will not break down an expression into factors, that’s what the factor()
function is for.
Here is a very simple expression on which we will apply the factor()
function.
from sympy import symbols, factor
x, y = symbols("x y")
expr = x**2 - x - 6
print(factor(expr))
(x - 3)*(x + 2)
Using the = (Equals) operator
If you try using =
in SymPy, you might not get the result you expect, as it’s regarded as the assignment operator. If it’s the =
you want to apply, there is a separate function with this ability in SymPy, which we can use instead.
The Eq()
function in SymPy returns an Eq
object, which we can then pass values into to check whether the “Equals to” relationship holds true or not. If the relationship held true, then the boolean value True
will be returned, else False
.
from sympy import symbols, Eq
x = symbols("x")
expr = Eq(x + 1, 4)
print(expr.subs(x, 3))
True
This marks the end of the Python SymPy Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.