47

I read in the manual of Numpy that there is function det(M) that can calculate the determinant. However, I can't find the det() method in Numpy.

By the way, I use Python 2.5. There should be no compatibility problems with Numpy.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234

2 Answers2

76

You can use numpy.linalg.det to compute the determinant of an array:

In [1]: import numpy

In [2]: M = [[1, 2], [3, 4]]

In [3]: print numpy.linalg.det(M)
Out[3]: -2.0000000000000004
Hamman Samuel
  • 2,350
  • 4
  • 30
  • 41
xyz
  • 1,242
  • 9
  • 13
32

For large arrays underflow/overflow may occur when using numpy.linalg.det, or you may get inf or -inf as an answer.

In many of these cases you can use numpy.linalg.slogdet (see documentation):

sign, logdet = np.linalg.slogdet(M)

where sign is the sign and logdet the logarithm of the determinant. You can calculate the determinant simply by:

det = np.exp(logdet)

For sparse matrices (2-D arrays), I highly recommend another approach based on LU decomposition.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234