📜  在Python中使用 NumPy 计算给定方阵的行列式

📅  最后修改于: 2022-05-13 01:55:10.248000             🧑  作者: Mango

在Python中使用 NumPy 计算给定方阵的行列式

在Python中,可以使用 NumPy 包轻松计算方阵的行列式。该包用于对单维和多维数组执行数学计算。 numpy.linalg是 NumPy 包的一个重要模块,用于线性代数。

我们可以使用 numpy.linalg 模块的det()函数来找出方阵的行列式。

示例 1: 2X2 矩阵的行列式。

Python3
# Importing libraries
import numpy as np
from numpy import linalg
  
# Creating a 2X2 matrix
matrix = np.array([[1, 0], [3, 6]])
print("Original 2-D matrix")
print(matrix)
  
# Output
print("Determinant of the 2-D matrix:")
print(np.linalg.det(matrix))


Python3
# Importing libraries
import numpy as np
from numpy import linalg
  
# Creating a 3X3 matrix
matrix = np.array([[1, 0, 1], [1, 2, 0], [4, 6, 2]])
print("Original 3-D matrix")
print(matrix)
  
# Output
print("Determinant of the 3-D matrix:")
print(np.linalg.det(matrix))


Python3
# Importing libraries
import numpy as np
from numpy import linalg
  
# Creating a 4X4 matrix
matrix = np.array([[1, 0, 1, 8], [1, 2, 0, 3], [4, 6, 2, 6], [0, 3, 6, 4]])
print("Original 4-D matrix")
print(matrix)
  
# Output
print("Determinant of the 4-D matrix:")
print(np.linalg.det(matrix))


输出:

Original 2-D matrix
[[1 0]
 [3 6]]
Determinant of the 2-D matrix:
6.0

示例 2: 3X3 矩阵的行列式

Python3

# Importing libraries
import numpy as np
from numpy import linalg
  
# Creating a 3X3 matrix
matrix = np.array([[1, 0, 1], [1, 2, 0], [4, 6, 2]])
print("Original 3-D matrix")
print(matrix)
  
# Output
print("Determinant of the 3-D matrix:")
print(np.linalg.det(matrix))

输出:

Original 3-D matrix
[[1 0 1]
 [1 2 0]
 [4 6 2]]
Determinant of the 3-D matrix:
2.0

示例 3: 4X4 矩阵的行列式

Python3

# Importing libraries
import numpy as np
from numpy import linalg
  
# Creating a 4X4 matrix
matrix = np.array([[1, 0, 1, 8], [1, 2, 0, 3], [4, 6, 2, 6], [0, 3, 6, 4]])
print("Original 4-D matrix")
print(matrix)
  
# Output
print("Determinant of the 4-D matrix:")
print(np.linalg.det(matrix))

输出:

Original 4-D matrix
[[1 0 1 8]
 [1 2 0 3]
 [4 6 2 6]
 [0 3 6 4]]
Determinant of the 4-D matrix:
188.0