Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the matrix determinant using Numpy?

People also ask

How do you find the determinant in Python?

Python has a numerical library called NumPy which has a function called numpy. linalg. det() to compute the value of a determinant.

What is matrix operations in NumPy?

It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array. Using NumPy, mathematical and logical operations on arrays can be performed.


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

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.