### Python determinant calculation(without the use of external libraries)

3

I'm making a small matrix operations library as a programming challenge to myself(and for the purpose of learning to code with Python), and I've come upon the task of calculating the determinant of 2x2, 3x3 and 4x4 matrices.

As far as my understanding of linear algebra goes, I need to implement the Rule of Sarrus in order to do the first 2, but I don't know how to tackle this Pythonically or for matrices of larger size. Any hints, tips or guides would be much appreciated.

2012-04-04 00:08
by trainreq
Read up on LU Decomposition. Once your matrix is LU decomposed, You can use the diagonal of the U matrix to calculate the determinant - Vlad the Impala 2012-04-04 00:21

6

The rule of Sarrus is only a mnemonic for solving 3x3 determinants, and won't be as helpful moving beyond that size.

You should investigate the Leibniz formula for calculating the determinant of an arbitrarily large square matrix. The nice thing about this formula is that the determinant of an `n*n` matrix is that it can be determined in terms of a combination of the determinants of some of its `(n-1)*(n-1)` sub-matrices, which lends itself nicely to a recursive function solution.

If you can understand the algorithm behind the Leibniz formula, and you have worked with recursive functions before, it will be straightforward to translate this in to code (Python, or otherwise), and then you can find the determinant of 4x4 matrices and beyond!

2012-04-04 00:19
by Jason LeBrun
Thank you, Jason - trainreq 2012-04-04 00:32

0

If M is matrix of floats, here is an ugly version of condensation method (chio?), i think it works...
i am using python 2.7.2

``````from itertools import product, islice

def det(M,prod=1):
dim = len(M)
if dim == 1:
return prod * M.pop().pop()
it = product(xrange(1,dim),repeat=2)
prod *= M
return det([[M[x][y]-M[x]*(M[y]/M) for x,y in islice(it,dim-1)] for i in xrange(dim-1)],prod)
``````
2012-04-05 22:50
by ChessMaster