如何使用 SciPy 庫來解線性方程?


SciPy 有一個名為 scipy.linalg.solve() 的函式用於解決線性方程。我們只需要知道如何用向量的形式表示線性方程。它將求解線性方程組 a * x = b 中未知數 x 的值。讓我們透過下面的例子來理解它:

示例

在這個例子中,我們將嘗試解決一個線性代數系統,可以表示如下:

   3x + 2y = 2

   x - y = 4

   5y + z = -1

函式 scipy.linalg.solve() 將找到 x、y 和 z 的值,使得以上三個方程都等於零。

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

更新於: 2021年11月24日

563 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告