Solving Linear Equations with NumPy!
In Linear Algebra, we solve systems of linear equations, and if we want to programmatically solve them, we can use Python’s Numpy library to do so. This article will show you how it’s done. Let’s get started.
First you need to install Numpy using Python’s package manager - PIP. Link
pip install numpy
To solve linear equations in Numpy, we need to utilize the Numpy Linear Algebra functions.
Let’s solve the following simple system of equations using Numpy!
\[ 3x + y = 5 \] \[ x + y = 3 \]
This trivial system of equations has the unique solution of
\[ (x,y) = (1,2) \]
To derive these answers programmitcally, we first need to write the coefficient of the equations in a Numpy array, like so
import numpy as np
coefficients = np.array([[3, 1], [1, 1]])
Next we need to define the right hand side of the equations in an numpy array as well, like so
import numpy as np
solutions = np.array([5,3])
Now we can solve this system using the Numpy Linear Algebra function ‘np.linalg.solve’
import numpy as np
coefficients = np.array([[3, 1], [1, 1]])
solutions = np.array([5,3])
x = np.linalg.solve(coefficients, solutions)
print(x) # prints [1,2]