SymPy is a symbolic library for python that allows a user to preform more complex mathematics like algebra, linear algebra, calculus and more.
SymPy provides a free online python interpreter which you can find here.
You can follow along with the examples in this section by using the SymPy Online Interpreter if you would like.
The real power of SymPy comes from the ability to use symbolic variables, variables that don't have an explicit values. This allows us to add variables into an equation without knowing what the value of that variable is. To create a symbolic variable we can use the following command:
x = symbols('x')
This seems like a strange command, why are we passing in a string? SymPy has to work around Python's existing syntax so when we send the above command we aren't setting x
to be a symbolic variable but instead linking x
to the string "x" inside of SymPy's symbols list (called a "buffer" below). (An entry inside of the symbols list is referred to as a symbolic object in this database, for example "x").
Lets consider another situation, we can assign multiple variables as symbols in a single command by using the following syntax: x,y,z = symbols('x,y,z')
. What would happen if we mess with the order of the variables?
x,y,z = symbols('x,z,y')
Now thats pretty confusing, after that command whenever we use y
in an equation we are really using z
instead:
In [2]: x,y,z = symbols('x,z,y')
In [3]: expr = 2*x + y
In [4]: print(expr)
2*x + z
But why do we care? If we always set the python variable to a symbolic variable of the same name we shouldn't have to worry about this right? Well consider the following case. Lets say that you are working through an algebra problem with 2 equations and 2 unknowns (
First you set up your symbolic variables, type in your equations, are are getting ready to use the solve function to find
In [2]: x,y = symbols('x,y')
In [3]: f = 2*x + y
In [4]: g = y**2
In [5]: y = solve(g, y)[0]
In [6]: x = solve(f, x)[0]
In [7]: print(x,y)
-y/2 0
Wait a second, why did x
return -y/2
instead of 0
? We already solved for y
, it should know its value. Well thinking back to how variables are linked to symbolic objects, we didn't actually set y = 0 when we solved for y, instead we broke our connection from the python variable y and the symbolic object y. The original x
and y
inside of our equation f
are not python variables but instead symbolic objects which don't have a value. To fix this we need to sub in the value we found for y
in for our symbolic variable y
:
In [16]: x.subs(symbols('y'), y)
Out[16]: 0
The subs
method can be applied to equations that include a symbolic variable and it takes in two arguments: the symbolic object to replace (symbols('y')
) and the value/object to replace it with (y
which is equal to 0 in this case).
See SymPy - Gotchas - Symbols for more information.