How to calculate the determinant of a matrix in NumPy (Python)

The det() function in NumPy returns the determinant of a matrix.

import numpy as np
from numpy import linalg

A = np.array([[1, 2], [3, 4]])
d = linalg.det(A)

print(d)
# -2.0000000000000004

print(type(d))
# <class 'numpy.float64'>

You can calculate determinants on this page. Let's input det and an array in the search form and press the Enter key.

Determinants of 2D matrices

import numpy as np
from numpy import linalg

A = np.array([[5, 7], [2, 3]])

det = linalg.det(A)

print(det)  # 0.9999999999999987

The actual determinant of A is precisely 1.

\[ \left| \begin{array}{cc} 5 & 7 \\ 2 & 3 \end{array} \right| = 1 \]

Determinants of 3D matrices

import numpy as np
from numpy import linalg

A = np.array([[3, 4, 5], [-1, 2, -3], [0, 1, 0]])

det = linalg.det(A)

print(det)  # 4.000000000000002

Determinants of identity matrices

import numpy as np
from numpy import linalg

i = np.identity(3)

print(i)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]

det = linalg.det(i)

print(det)  # 1.0

Dimension error

import numpy as np
from numpy import linalg

A = np.array([[3, 4, 5], [-1, 2, -3]])

det = linalg.det(A)

# numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square

NumPy Matrix

NumPy Tutorial