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]:
Let us print Integration symbol.
In [20]:
Integral(sqrt(1/x))
Out[20]:
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]:
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]:
Let us solve the above equation for "a" now.
In [29]:
solve(x**2 - 4*a - 4, a)
Out[29]:
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]:
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]:
Related Notebooks
- How to Visualize Data Using Python - Matplotlib
- How to Create DataFrame in R Using Examples
- How to Generate Random Numbers in Python
- How To Read CSV File Using Python PySpark
- How To Analyze Wikipedia Data Tables Using Python Pandas
- How To Read JSON Data Using Python Pandas
- How To Plot Unix Directory Structure Using Python Graphviz
- How to do SQL Select and Where Using Python Pandas
- How to Plot a Histogram in Python