我们如何使用 SciPy 库来求解线性方程?
SciPy有一个名为scipy的函数。求解线性方程组。我们只需要知道如何用向量表示线性方程。它将求解未知x的线性方程组a*x=b。让我们借助以下示例来理解它-linalg.solve()
示例
在这个例子中,我们将尝试解决一个线性代数系统,它可以给出如下-
3x+2y=2
x-y=4
5y+z=-1
函数scipy。将找到所有上述三个方程都为零的x、y和z值。linalg.solve()
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输出结果
[[ 2.] [-2.] [ 9.]]
让我们再看一个例子-
示例
在这个例子中,我们将解决一个更复杂的线性代数系统,如下所示-
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输出结果
[[ 2.] [-1.] [ 1.]]