Calculating Python determinant (without using external libraries)

I am making a small matrix operating library as a programming challenge to myself (and for the purpose of learning code from Python) and I am faced with the task of calculating the determinant of 2x2, 3x3 and 4x4 matrices.

As far as I understand linear algebra, I need to implement the Sarrus rule to make the first 2, but I don't know how to handle this Pythonically or for larger matrices. Any hints, tips, or guidance would be much appreciated.

+3


source to share


2 answers


The Sarrus Rule is only a mnemonic for solving 3x3 determinants and would not be as useful as moving beyond that size.

You should investigate Leibniz's formula for calculating the determinant of an arbitrarily large square matrix. The best part about this formula is that the determinant of a matrix n*n

is that it can be defined in terms of a combination of determinants of some of its submatrices (n-1)*(n-1)

that lends itself well to recursive functional solutions.



If you can understand the algorithm behind Leibniz's formula and you've worked with recursive functions before, it would be easy to translate that into code (Python or otherwise), and then you can find the determinant of 4x4 matrices and beyond!

+6


source


If M is a matrix of floats, here is an ugly version of the 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[0][0]
    return det([[M[x][y]-M[x][0]*(M[0][y]/M[0][0]) for x,y in islice(it,dim-1)] for i in xrange(dim-1)],prod)

      

0


source







All Articles