How to Solve Simulataneous Equations with Python

Python in combination with Numpy allows for using python to solve simultaneous equations in a few simple steps. Using python to solve simultaneous equations relies on matrix linear algebra and can be done by using a built-in function (method 1) or manually (method 2) manually manipulating the matrices to solve.

So how to solve simultaneous equations with python? For our example we will be using the following two equations:

5x + 3y =40

x + 2y = 18

Method 1

Step 1

Convert the system of equations to matrix form:

For our example we have:

Step 2

Import the numpy module and write the matrices as numpy arrays.

import numpy as np

Step 3

Define coefficient and results matrices as numpy arrays

A = np.array([[5,3],[1,2]])
B = np.array([40,18])

Step 4

Use numpy’s linear algebra solve function to solve the system

C = np.linalg.solve(A,B)

C is now an array with the value of the variables. Type C and press enter to see the values, this is how method 1 solves simultaneous equations.

print(C)
[ 3.71428571,  7.14285714]

Full code

import numpy as np 
A = np.array([[5,3], [1,2]])
B = np.array([40,18])
C = np.linalg.solve(A, B)
print(C)
    

Method 2

Step 1

Convert the system of equations to matrix form as before:

Step 2

As before, we import the numpy module and write the matrices as numpy arrays.

import numpy as np

A = np.array([[5,3],[1,2]])
B = np.array([40,18])

Step 3

Use numpy’s linear algebra inv function to find the inverse of matrix A

D = np.linalg.inv(A)

Step 4

Use numpy’s dot function to find the dot product of the inverse of the coefficient matrix and the results matrix

E=np.dot(D,B)

E is now an array with the value of the variables. Type E and press enter to see the values.

print(E)
array([ 3.71428571, 7.14285714])

This is the same answer that we obtained using the first method.

Full Code

import numpy as np
A = np.array([[5,3], [1,2]])
B = np.array([40,18])
D = np.linalg.inv(A)
E = np.dot(D,B)
print E
    

Thanks for reading, if you like this post and now know how to solve simultaneous equations with python, please don't forget to share with your friends and followers using the buttons below. 

Happy coding :)