Solving linear equations in Python for those who haven’t experienced it before might be a bit confusing. As a Python developer who focuses more on web development, I am quite a novice especially when it comes to the very basic and mathematical things. Those include solving 4 variable linear equations. Actually, the number of the variable doesn’t really matter, this post is still relevant. In this post, I would like to share my experience in solving mathematical linear equations using the NumPy module in Python.
The basics of linear equations
Most of you might already know this. You could skip this part if you like. According to this Wikipedia article, a linear equation is an equation that has variables (or unknowns or indeterminates), coefficients, and constants. To make it easier for you, here is a big picture of how linear equations look like.
Above is an example of a 4 variable linear equation. From that equation, \(a\)
A linear equation does not always look like the example above, they could be in a different form. But, they are basically the same. For example, this \(2+a+b+c=d\) equation looks different from the example above, but it is the same. To make it look alike, you could change it into this \(a+b+c-d=-2\) equation. Eventually, it is just the orders of variables, coefficients, and constants. Orders don’t really matter.
The NumPy approach
In this section, I am assuming that you already have the basics of linear equations. At least, you know how to differentiate between variables, coefficients, and constants. So, let’s assume that you have the following equations and you need to solve them.
Solving it using NumPy
I will be pretty straightforward here. At first, you have to make sure that you have imported NumPy.
import numpy as np
I imported NumPy as
np just to make it look neat. I will create two variables containing NumPy arrays.
coef = np.array([ [1, 1, 1, 1], [2, 3, -1, 1], [1, -1, 1, -1], [1, 2, 3, -1] ]) result = np.array([4, 10, -2, -1])
If you look closer, the
coef variable is a two-dimensional NumPy array containing the coefficients of the equations in the order of a, b, c, then d. Please note that you need to be consistent when inputting coefficients into a NumPy array. On the other side, the
result variable consists of the constants that are usually on the right side of an equation (the result).
After you create those arrays, you are almost done. The next thing to do is to call
a, b, c, d = np.linalg.solve(coef, result) print('a:', a, 'b:', b, 'c:', c, 'd:', d)
That’s it! Now, you have solved the a, b, c, and d variable of the above linear equations. Next, you might want to process those outputs furthermore.
At the end of the day, you have just mastered a basic knowledge about linear equations and the usage of the NumPy module in Python. Next, you might want to click on one of these extra resources to step up your knowledge.