Loading [MathJax]/jax/output/HTML-CSS/jax.js

在 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))

示例

Open Compiler
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))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

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

更新于: 2022年2月25日

10K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告