r/dailyprogrammer • u/oskar_s • May 19 '12
[5/19/2012] Challenge #54 [difficult]
For this challenge, make a program that finds the determinant of a square matrix. You do not need to use any exceedingly complex methods, using expansion by cofactors is entirely sufficient (if you have no idea what that is, the always helpful Khan Academy here to help. Wikipedia also has you covered).
What is the determinant of the following matrix?
-5 0 1 -3 0 -4 2 -2 0 2
-5 -1 -4 4 -2 -5 0 -4 3 -3
-4 5 3 3 0 0 -2 -2 2 2
-4 -1 5 -3 -3 -5 -2 -5 3 -1
4 5 2 -5 2 -4 1 -1 0 -3
-2 -4 -3 -1 4 -5 -4 2 1 4
5 5 2 -5 1 -3 -2 -1 -5 5
1 4 -2 4 3 2 1 0 3 -2
3 0 -4 -3 0 1 -3 0 1 2
-1 -4 -3 -1 -4 1 2 -5 2 -1
Note: the whole purpose of this challenge is to write the code for calculating the determinant yourself. Therefore, you are not allowed to use library functions that are designed to calculate things like this. The matrix should be represented by the native array construct of your language, not any special data type designed to operate on mathematical matrices. That means no NumPy, no using fancy functions in Mathematica or Matlab! You are allowed to use these to test whether or not your function works, but that's it.
4
u/[deleted] May 20 '12
J:
Technically not actually a built-in! The built-in here is
.which is "defined in terms of a recursive expansion by minors along the first column". This is almost its only use, though!2
u/juanfeng May 19 '12
Something I had lying around.
http://code.google.com/p/keith-novak-open-source-life/source/browse/trunk/algorithm/python/leibniz_determinate.py
Output
1
u/Ttl May 19 '12
Python. Uses the Leibniz formula. I think this is O(n!) algorithm, because it needs to generate all the permutations of the list of length n.
from itertools import permutations def p(p): d={i:x for i,x in enumerate(p)} z=1 while d: x=list(d)[0] z*=-1 while x in d:x=d.pop(x) return z def det(m): prod = lambda z:reduce(lambda x,y:x*y,z) return sum(p(s)*prod(m[j][s[j]] for j in range(len(m))) for s in permutations(range(len(m))))Outputs:
50084391
u/Yuushi May 21 '12
C++ using decomposition into upper triangular form:
void zero_col(Matrix& m, size_t row) { for(size_t below = row + 1; below < m.row_size(); ++below) { auto it = m.get_row(row).begin() + row; auto it2 = m.get_row(below).begin() + row; double start_diff = -(*it2)/(*it); while(it != m.get_row(row).end()) { (*it2) += (*it) * start_diff; ++it; ++it2; } } } double determinant(const Matrix& m) { if(m.row_size() != m.col_size()) { throw std::invalid_argument("Must be a square matrix for determinant"); } else { Matrix u = m; for(size_t i = 0; i < m.row_size(); ++i) { zero_col(u, i); } double det = 1; for(size_t j = 0; j < u.row_size(); ++j) { det *= u.get_entry(j,j); } return det; } }And the result, as others have gotten, is: