This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

15.2. Solving equations and inequalities

In [ ]:
from sympy import *
In [ ]:
var('x y z a')

Use the function solve to resolve equations (the right hand side is always 0).

In [ ]:
solve(x**2 - a, x)

You can also solve inequations. You may need to specify the domain of your variables. Here, we tell SymPy that x is a real variable.

In [ ]:
x = Symbol('x')
solve_univariate_inequality(x**2 > 4, x)

Systems of equations

This function also accepts systems of equations (here a linear system).

In [ ]:
solve([x + 2*y + 1, x - 3*y - 2], x, y)

Non-linear systems are also supported.

In [ ]:
solve([x**2 + y**2 - 1, x**2 - y**2 - S(1)/2], x, y)

Singular linear systems can also be solved (here, there are infinitely many equations because the two equations are colinear).

In [ ]:
solve([x + 2*y + 1, -x - 2*y - 1], x, y)

Now, let's solve a linear system using matrices with symbolic variables.

In [ ]:
var('a b c d u v')

We create the augmented matrix, which is the horizontal concatenation of the system's matrix with the linear coefficients, and the right-hand side vector.

In [ ]:
M = Matrix([[a, b, u], [c, d, v]]); M
In [ ]:
solve_linear_system(M, x, y)

This system needs to be non-singular to have a unique solution, which is equivalent to say that the determinant of the system's matrix needs to be non-zero (otherwise the denominators in the fractions above are equal to zero).

In [ ]:

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).