Can anyone tell me which is the best algorithm to find the value of determinant of a matrix of size N x N
?
The value of the determinant of a matrix can be calculated by the following procedure: For each element of the first row or first column get the cofactor of those elements. Then multiply the element with the determinant of the corresponding cofactor. Finally, add them with alternate signs.
The simplest way (and not a bad way, really) to find the determinant of an nxn matrix is by row reduction. By keeping in mind a few simple rules about determinants, we can solve in the form:
det(A) = α * det(R), where R is the row echelon form of the original matrix A, and α is some coefficient.
Finding the determinant of a matrix in row echelon form is really easy; you just find the product of the diagonal. Solving the determinant of the original matrix A then just boils down to calculating α as you find the row echelon form R.
If B is a matrix obtained by multiplying a row of A by some non-zero constant ß, then
det(B) = ß * det(A)
If B is a matrix obtained by swapping two rows of A, then
det(B) = -det(A)
If B is a matrix obtained by adding a multiple of one row to another row in A, then
det(B) = det(A)
Note that you can find the determinant, in most cases, with only Rule 3 (when the diagonal of A has no zeros, I believe), and in all cases with only Rules 2 and 3. Rule 1 is helpful for humans doing math on paper, trying to avoid fractions.
(I do unnecessary steps to demonstrate each rule more clearly)
| 2 3 3 1 | A=| 0 4 3 -3 | | 2 -1 -1 -3 | | 0 -4 -3 2 | R2 R3, -α -> α (Rule 2) | 2 3 3 1 | -| 2 -1 -1 -3 | | 0 4 3 -3 | | 0 -4 -3 2 | R2 - R1 -> R2 (Rule 3) | 2 3 3 1 | -| 0 -4 -4 -4 | | 0 4 3 -3 | | 0 -4 -3 2 | R2/(-4) -> R2, -4α -> α (Rule 1) | 2 3 3 1 | 4| 0 1 1 1 | | 0 4 3 -3 | | 0 -4 -3 2 | R3 - 4R2 -> R3, R4 + 4R2 -> R4 (Rule 3, applied twice) | 2 3 3 1 | 4| 0 1 1 1 | | 0 0 -1 -7 | | 0 0 1 6 | R4 + R3 -> R3 | 2 3 3 1 | 4| 0 1 1 1 | = 4 ( 2 * 1 * -1 * -1 ) = 8 | 0 0 -1 -7 | | 0 0 0 -1 |
def echelon_form(A, size): for i in range(size - 1): for j in range(size - 1, i, -1): if A[j][i] == 0: continue else: try: req_ratio = A[j][i] / A[j - 1][i] # A[j] = A[j] - req_ratio*A[j-1] except ZeroDivisionError: # A[j], A[j-1] = A[j-1], A[j] for x in range(size): temp = A[j][x] A[j][x] = A[j-1][x] A[j-1][x] = temp continue for k in range(size): A[j][k] = A[j][k] - req_ratio * A[j - 1][k] return A
Here is an extensive discussion.
There are a lot of algorithms.
A simple one is to take the LU
decomposition. Then, since
det M = det LU = det L * det U
and both L
and U
are triangular, the determinant is a product of the diagonal elements of L
and U
. That is O(n^3)
. There exist more efficient algorithms.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With