在 Python 中解決線性矩陣方程或線性標量方程組
要解決線性矩陣方程,請在 Python 中使用 numpy.linalg.solve() 方法。該方法計算完全確定的(即滿秩)線性矩陣方程 ax = b 的“精確”解 x。返回系統 a x = b 的解。返回的形狀與 b 相同。第一個引數 a 是係數矩陣。第二個引數 b 是縱座標或“因變數”值。
步驟
首先,匯入所需的庫 -
import numpy as np
使用 array() 方法建立兩個二維 numpy 陣列。考慮方程組 x0 + 2 * x1 = 1 和 3 * x0 + 5 * x1 = 2 -
arr1 = np.array([[1, 2], [3, 5]]) arr2 = np.array([1, 2])
顯示陣列 -
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)檢查兩個陣列的維度 -
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)檢查兩個陣列的形狀 -
Print(“\nShape of Array1…\n”,arr1.shape)
print("\nShape of Array2...\n",arr2.shape)要解決線性矩陣方程,請使用 numpy.linalg.solve() 方法 -
print("\nResult...\n",np.linalg.solve(arr1, arr2))示例
import numpy as np
# Creating two 2D numpy arrays using the array() method
# Consider the system of equations x0 + 2 * x1 = 1 and 3 * x0 + 5 * x1 = 2
arr1 = np.array([[1, 2], [3, 5]])
arr2 = np.array([1, 2])
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To solve a linear matrix equation, use the numpy.linalg.solve() method in Python.
print("\nResult...\n",np.linalg.solve(arr1, arr2))輸出
Array1... [[1 2] [3 5]] Array2... [1 2] Dimensions of Array1... 2 Dimensions of Array2... 1 Shape of Array1... (2, 2) Shape of Array2... (2,) Result... [-1. 1.]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP