My Coding > Programming language > Python > Python libraries and packages > Python NumPy > NumPy: How to solve system of linear equations

NumPy: How to solve system of linear equations

Solving of the system of linear equations is a very common task in modern science. In this short tutorial I will solve system of 4 linear equations with NumPy library in Python.


3*x1 + 2*x2 - x3 + x4 = 28
x1 - 4*x2 + 3*3 + 2*x4 = -23
2*x1 - x2 - 2*x3 - 4*x4 = 2
8*x1 + x2 - 9*x3 + 5*x4 = 25

Now, nobody solve these kind of equations as a system of equations. Everybody use matrices to solve it.

AX = B

or in more details:

32-11x1 = 28
1-432x2-23
2-1-2-4x32
81-95x425

Matrix solution is pretty simple

X = A-1B

where A-1 is an inverse of the A matrix. So AA-1 = I

Solving with NumPy

Solving with matrix equation

First of all, we need to prepare all data:


import numpy as np
a = np.array([[3, 2, -1, 1], [1, -4, 3, 2], [2, -1, -2, -4], [8, 1, -9, 5]])
b = np.array([28, -23, 2, 25])

Then we need to find inverse of the A matrix


inv_a = np.linalg.inv(a)
print(inv_a)
#[[ 0.27536232  0.10803689  0.10144928 -0.0171278 ]
# [ 0.23188406 -0.12911726 -0.07246377 -0.05270092]
# [ 0.24637681  0.10144928 -0.01449275 -0.10144928]
# [-0.04347826  0.03557312 -0.17391304  0.05533597]]

And then the solution will be the dot product of inverse of the matrix A to vector B. Also we can check the solution with using our vector X in our original dot product AX and check that this vector is collinear to B


x = np.linalg.inv(a).dot(b)
print(x)
# [ 5.  8.  2. -1.]
print(np.allclose(np.dot(a, x), b))
# True

Solving with build in NumPy function linalg.solve

It is not necessary to use all this linear algebra equations. NumPy already have all required functions in linalg library


import numpy as np
a = np.array([[3, 2, -1, 1], [1, -4, 3, 2], [2, -1, -2, -4], [8, 1, -9, 5]])
b = np.array([28, -23, 2, 25])
x = np.linalg.solve(a, b)
print(x) # [ 5.  8.  2. -1.]


Published: 2022-06-18 02:13:13
Updated: 2022-06-18 02:14:09

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.