How To Solve Linear Equations Using Sympy In Python

Sympy is a great library for symbolic mathematics.

In :
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 :
init_printing()
var('x y z a')
Out:
$\displaystyle \left( x, \ y, \ z, \ a\right)$

Let us print Integration symbol.

In :
Integral(sqrt(1/x))
Out:
$\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 :
solve(x**2 - a, x)
Out:
$\displaystyle \left[ - \sqrt{a}, \ \sqrt{a}\right]$

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

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

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

In :
solve(x**2 - 4*a - 4, a)
Out:
$\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 :
solve((x + 5*y - 2, -3*x + 6*y - 15), x, y)
Out:
$\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 :
x, y = symbols('x, y')
linsolve([x + 5*y + -2, -3*x + 6*y - 15], (x, y))
Out:
$\displaystyle \left\{\left( -3, \ 1\right)\right\}$