How can we use the SciPy library to solve a Linear equation?


SciPy has a function called scipy.linalg.solve() to solve linear equations. All we need to know is how we can represent our linear equation in terms of vectors. It will solve the linear equation set a * x = b for the unknown x. Let’s understand it with the help of below example −

Example

In this example, we will be trying to solve a linear algebra system which can be given as follows −

   3x + 2y = 2

   x - y = 4

   5y + z = -1

The function scipy.linalg.solve() will find the values of x, y, and z for which all the above three equations are zero.

import numpy as np
from scipy import linalg

# The linear algebra system which is given as

# 3x + 2y = 2

# x - y = 4

# 5y + z = -1

#We need to find values of x,y and z for which all these equations are zero

# Creating the input array
a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])

# Providing the solution Array
b = np.array([[2], [4], [-1]])

# Solve the linear algebra
x = linalg.solve(a, b)

# Printing the result
print(x)

# Checking the result
np.dot(a, x) == b

Output

[[ 2.]
[-2.]
[ 9.]]

Let’s see one more example −

Example

In this example we will solve a bit more complex linear algebra system as given below −

x + 2y - 3z = -3

2x - 5y + 4z = 13

5x + 4y - z = 5

import numpy as np
from scipy import linalg

# Creating the input array
a = np.array([[1, 2, -3], [2, -5, 4], [5, 4, -1]])

# Providing the solution Array
b = np.array([[-3], [13], [5]])

# Solve the linear algebra
x = linalg.solve(a, b)

# Printing the result
print(x)

# Checking the result
np.dot(a, x) == b

Output

[[ 2.]
[-1.]
[ 1.]]

Updated on: 24-Nov-2021

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements