Python 行列式
矩阵的行列式是仅与方阵相关的标量。 对于方阵 [[1,2], [3,4]]
,行列式计算为 (1x4) - (2x3)
。
在Python中使用numpy.linalg.det()计算矩阵的行列式
NumPy 包有一个名为 linalg 的模块,它代表线性代数。 该模块提供了一个内置方法 det()
来计算 Python 中矩阵的行列式。
要使用 NumPy 包,我们必须首先使用以下命令安装它。
#Python 3.x
pip install numpy
安装后,我们可以使用以下语法求任意方阵的行列式。
句法:
#Python 3.x
numpy.linalg.det(matrix)
Python 中 2x2 矩阵的行列式
在下面的代码中,我们创建了一个 2x2 NumPy 数组,并使用 det()
方法计算了矩阵的行列式。 最后,我们对行列式进行了四舍五入,因为此方法将行列式返回为浮点数据类型。
示例代码:
#Python 3.x
import numpy as np
matrix = np.array([[7, 5], [2, 4]])
det = np.linalg.det(matrix)
print("Determinant of the matrix is:", round(det))
输出:
#Python 3.x
Determinant of the matrix is: 18
Python 中 3x3 矩阵的行列式
我们可以使用相同的过程计算 3x3 或任何维度的方阵的行列式。 在下面的代码中,我们构造了一个 3x3 NumPy 数组,并使用 det() 方法来确定矩阵的行列式。
示例代码:
#Python 3.x
import numpy as np
matrix = np.array([[7, 5, 3], [2, 4, 1], [5, 8, 6] ])
det = np.linalg.det(matrix)
print("Determinant of the matrix is:", round(det))
输出:
#Python 3.x
Determinant of the matrix is: 65
使用 symPy 库在 Python 中计算矩阵的行列式
symPy 是 Python 中用于符号计算的开源库。 我们可以使用这个库执行各种代数和其他数学运算。
要使用 symPy,我们必须首先使用以下命令安装它。
#Python 3.x
pip install sympy
Python 中 2x2 矩阵的行列式
我们在以下代码中使用 sympy.Matrix()
方法创建了一个 2x2 矩阵。 然后我们通过调用矩阵的 det() 方法找到了行列式。
示例代码:
#Python 3.x
import sympy as sp
matrix=sp.Matrix([[7 , 5],[2 , 4]])
determinant=matrix.det()
print("Determinant of the matrix is:", determinant)
输出:
#Python 3.x
Determinant of the matrix is: 18
Python 中 3x3 矩阵的行列式
对于 3x3 矩阵或任意维度的方阵,求行列式的过程是相同的。 在下面的代码中,我们创建了一个 3x3 矩阵,并使用该矩阵的 det()
方法找到了它的行列式。
示例代码:
#Python 3.x
import sympy as sp
matrix=sp.Matrix([[7, 5, 3], [2, 4, 1], [5, 8, 6] ])
determinant=matrix.det()
print("Determinant of the matrix is:", determinant)
输出:
#Python 3.x
Determinant of the matrix is: 65
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串