- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.]]
Advertisements