如何使用 SciPy 库来解线性方程?


SciPy 有一个名为 scipy.linalg.solve() 的函数用于解决线性方程。我们只需要知道如何用向量的形式表示线性方程。它将求解线性方程组 a * x = b 中未知数 x 的值。让我们通过下面的例子来理解它:

示例

在这个例子中,我们将尝试解决一个线性代数系统,可以表示如下:

   3x + 2y = 2

   x - y = 4

   5y + z = -1

函数 scipy.linalg.solve() 将找到 x、y 和 z 的值,使得以上三个方程都等于零。

Open Compiler
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.]]

让我们再看一个例子:

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

在这个例子中,我们将解决一个稍微复杂一点的线性代数系统,如下所示:

x + 2y - 3z = -3

2x - 5y + 4z = 13

5x + 4y - z = 5

Open Compiler
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.]]

更新于: 2021年11月24日

563 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告