How to solve system of linear equations with Numpy

In this tutorial, we will learn how to solve a system of linear equations in Python using Numpy. We will see two examples, first with a system of linear equations with two unknowns and. two variables. And the with a system of linear equations with three unknowns and three equations. We will use Numpy’s linalg.solve() function solve these equations.

The basic syntax of linalg.solve function is

linalg.solve(coeff_matrix, constant_vector)

System of Linear Equations

A system of linear equations consists of multiple linear equations with the same variables. Solving a system of linear equations requires finding the values of the unknown variables that satisfy all the equations simultaneously.

For example, here is a simple system of linear equations.

2x + y = 8
x + 3y = 14

Here we two equations with two unknown variables x and y. The aim of solving this system of linear equations is to find the values of x. and. y, for which the equations hold true.

For example, when x= 2 and y=4, both the first equation (2×2 + 4 = 8) and the. second equation (2 + 3*4 = 14) hold true. And we have found a solution for the system of equations.

We can write the system of equations in a matrix form

Ax = b

Where A is a 2×2 matrix with coefficients of the equation, x is the variables, and b are the constants.

A = np.array([[2, 1],
             [1, 3]])
b = np.array([8,14])

Solving a System of Linear Equations with Numpy

We can use Numpy’s linalg.solve() function solve this system of linear equations in matrix form by providing the coefficient matrix A and b as arguments.

np.linalg.solve(A, b)

[2,4]

And we get the same solution from Numpy’s linalg.solve as the one we found manually.

Solving a System of Linear Equations with 3 unknowns in Numpy

Numpy’s linalg.solve can be handy in a more complex system of linear equation. Here is an example of solving a system of linear equations with three variables.

3x + 2y - z = 1
2x - 2y + 4z = -2
-x + 0.5y -z = 0

As before, we can write this system of linear equations in matrix for Ax =b where A is

A = np.array([[3,2,-1], 
              [2,-2,4],
              [-1,0.5,-1]])

Now we have the coefficients of the equations as a Numpy array.

A
array([[ 3. ,  2. , -1. ],
       [ 2. , -2. ,  4. ],
       [-1. ,  0.5, -1. ]])

And the constant b is

b = np.array([1, -2,0])
b

array([ 1, -2,  0])

With A and b in hour hand, we can use Numpy’s linalg.solve() function to solve for the values x,y,and z that will make the equations hold true.

np.linalg.solve(a, b)

array([ 1., -2., -2.])

For our example, we get the solution as [1,-2,-2]. We can plugin the values and verify the system of linear equations.

In short, Numpy’s linalg.solve function is a convenient and efficient way to solve systems of linear equations in Python. It can be used to solve systems of equations with any number of variables, making it a useful tool for a wide range of applications.