*52*

To solve a system of equations in Python, we can use functions from the NumPy library.

The following examples show how to use NumPy to solve several different systems of equations in Python.

**Example 1: Solve System of Equations with Two Variables**

Suppose we have the following system of equations and weâ€™d like to solve for the values of x and y:

5x + 4y = 35

2x + 6y = 36

The following code shows how to use NumPyÂ to solve for the values of x and y:

import numpy as np #define left-hand side of equation left_side = np.array([[5, 4], [2, 6]]) #define right-hand side of equation right_side = np.array([35, 36]) #solve for x and y np.linalg.inv(left_side).dot(right_side) array([3., 5.])

This tells us that the value for x is **3** and the value for y is **5**.

**Example 2: Solve System of Equations with Three Variables**

Suppose we have the following system of equations and weâ€™d like to solve for the values of x, y, and z:

4x + 2y + 1z = 34

3x + 5y â€“ 2z = 41

2x + 2y + 4z = 30

The following code shows how to use NumPy to solve for the values of x, y, and z:

import numpy as np #define left-hand side of equation left_side = np.array([[4, 2, 1], [3, 5, -2], [2, 2, 4]]) #define right-hand side of equation right_side = np.array([34, 41, 30]) #solve for x, y, and z np.linalg.inv(left_side).dot(right_side) array([5., 6., 2.])

This tells us that the value for x is **5**, the value for y is **6**, and the value for z is **2**.

**Example 3: Solve System of Equations with Four Variables**

Suppose we have the following system of equations and weâ€™d like to solve for the values of w, x, y, and z:

6w + 2x + 2y + 1z = 37

2w + 1x + 1y + 0z = 14

3w + 2x + 2y + 4z = 28

2w + 0x + 5y + 5z = 28

The following code shows how to use NumPy to solve for the values of w, x, y, and z:

import numpy as np #define left-hand side of equation left_side = np.array([[6, 2, 2, 1], [2, 1, 1, 0], [3, 2, 2, 4], [2, 0, 5, 5]]) #define right-hand side of equation right_side = np.array([37, 14, 28, 28]) #solve for w, x, y, and z np.linalg.inv(left_side).dot(right_side) array([4., 3., 3., 1.])

This tells us that the value for w is **4**, x is **3**, y is **3**, and z is **1**.

**Additional Resources**

The following tutorials explain how to solve a system of equations using other statistical software:

How to Solve a System of Equations in R

How to Solve a System of Equations in Excel