diff --git a/LinearAlgebraPurePython.py b/LinearAlgebraPurePython.py index 2b1f87a..ccaf130 100644 --- a/LinearAlgebraPurePython.py +++ b/LinearAlgebraPurePython.py @@ -326,9 +326,20 @@ def determinant_fast(A): AM = copy_matrix(A) # Section 2: Row manipulate A into an upper triangle matrix + odd_swaps = False for fd in range(n): # fd stands for focus diagonal - if AM[fd][fd] == 0: - AM[fd][fd] = 1.0e-18 # Cheating by adding zero + ~zero + if AM[fd][fd] == 0: # Do a row swap with a row that won't result in a pivot of 0 + found = False + for i in range(fd+1,n): + if AM[i][fd] != 0: + temp = AM[fd] + AM[fd] = AM[i] + AM[i] = temp + found = True + odd_swaps = not odd_swaps + break + if not found: + return 0 # If there are no other rows that can do that then return the determinant of 0 for i in range(fd+1, n): # skip row with fd in it. crScaler = AM[i][fd] / AM[fd][fd] # cr stands for "current row". for j in range(n): # cr - crScaler * fdRow, one element at a time. @@ -338,7 +349,8 @@ def determinant_fast(A): product = 1.0 for i in range(n): product *= AM[i][i] # ... product of diagonals is determinant - + if odd_swaps: + product *= -1 return product