How To Solve Linear Equations Using Sympy In Python

Sympy is a great library for symbolic mathematics.

In [18]:
import sympy as sp
from sympy import *

Before delve deeper in to solving linear equations, let us see how we can print actual mathematical symbols easily using Sympy.

Pretty print in ipython notebook

In [19]:
init_printing()
var('x y z a')
Out[19]:
$\displaystyle \left( x, \ y, \ z, \ a\right)$

Let us print Integration symbol.

In [20]:
Integral(sqrt(1/x))
Out[20]:
$\displaystyle \int \sqrt{\frac{1}{x}}\, dx$

Solve Linear Equations Using Sympy

Let us solve a simple linear equation, x^2-a=0

Let us solve for x.

In [21]:
solve(x**2 - a, x)
Out[21]:
$\displaystyle \left[ - \sqrt{a}, \ \sqrt{a}\right]$

Let us do an another one, x^2 - 4a - 4 = 0. Let us solve for x.

In [28]:
solve(x**2 - 4*a - 4, x)
Out[28]:
$\displaystyle \left[ - 2 \sqrt{a + 1}, \ 2 \sqrt{a + 1}\right]$

Let us solve the above equation for "a" now.

In [29]:
solve(x**2 - 4*a - 4, a)
Out[29]:
$\displaystyle \left[ \frac{x^{2}}{4} - 1\right]$

Solve System Of Linear Equations

Let us solve following two equations...

x + 5*y - 2 = 0

-3x + 6y - 15 = 0

In [31]:
solve((x + 5*y - 2, -3*x + 6*y - 15), x, y)
Out[31]:
$\displaystyle \left\{ x : -3, \ y : 1\right\}$

Note the syntax x,y above, since we are solving for both x and y.

Solve Linear Equations Using linsolve

Sympy has another library which is called livsolve which can be used to solve the linear equations.

from sympy.solvers.solveset import linsolve

Let us solve below equations again using linsolve.

x + 5*y - 2 = 0

-3x + 6y - 15 = 0

In [39]:
x, y = symbols('x, y')
linsolve([x + 5*y + -2, -3*x + 6*y - 15], (x, y))
Out[39]:
$\displaystyle \left\{\left( -3, \ 1\right)\right\}$