Solving Systems of Linear Equations with Python's Numpy - Stack Abuse

Solving Systems of Linear Equations with Python's Numpy

The Numpy library can be used to perform a variety of mathematical/scientific operations such as matrix cross and dot products, finding sine and cosine values, Fourier transform and shape manipulation, etc. The word Numpy is short-hand notation for "Numerical Python".

In this article, you will see how to solve a system of linear equations using Python's Numpy library.

What is a System of Linear Equations?

Wikipedia defines a system of linear equations as:

In mathematics, a system of linear equations (or linear system) is a collection of two or more linear equations involving the same set of variables.

The ultimate goal of solving a system of linear equations is to find the values of the unknown variables. Here is an example of a system of linear equations with two unknown variables, x and y:

Equation 1:

4x  + 3y = 20
-5x + 9y = 26


To solve the above system of linear equations, we need to find the values of the x and y variables. There are multiple ways to solve such a system, such as Elimination of Variables, Cramer's Rule, Row Reduction Technique, and the Matrix Solution. In this article we will cover the matrix solution.

In the matrix solution, the system of linear equations to be solved is represented in the form of matrix AX = B. For instance, we can represent Equation 1 in the form of a matrix as follows:

A = [[ 4   3]
[-5   9]]

X = [[x]
[y]]

B = [[20]
[26]]


To find the value of x and y variables in Equation 1, we need to find the values in the matrix X. To do so, we can take the dot product of the inverse of matrix A, and the matrix B as shown below:

X = inverse(A).B


If you are not familiar with how to find the inverse of a matrix, take a look at this link to understand how to manually find the inverse of a matrix. To understand the matrix dot product, check out this article.

Solving a System of Linear Equations with Numpy

From the previous section, we know that to solve a system of linear equations, we need to perform two operations: matrix inversion and a matrix dot product. The Numpy library from Python supports both the operations. If you have not already installed the Numpy library, you can do with the following pip command:

Conclusion

The article explains how to solve a system of linear equations using Python's Numpy library. You can either use linalg.inv() and linalg.dot() methods in chain to solve a system of linear equations, or you can simply use the solve() method. The solve() method is the preferred way.

Last Updated: February 23rd, 2020

Get tutorials, guides, and dev jobs in your inbox.

Prepping for an interview?

• Improve your skills by solving one coding problem every day
• Get the solutions the next morning via email
• Practice on actual problems asked by top companies, like:

Better understand your data with visualizations

•  30-day no-questions refunds