From c82370afcc5fa397d0b062edbcc1ff27e12e4372 Mon Sep 17 00:00:00 2001 From: RandomGamingDev <83996185+RandomGamingDev@users.noreply.github.com> Date: Fri, 24 Nov 2023 00:38:01 -0500 Subject: [PATCH 1/2] Fixed `determinant_fast()` --- LinearAlgebraPurePython.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/LinearAlgebraPurePython.py b/LinearAlgebraPurePython.py index 2b1f87a..ed5c4f4 100644 --- a/LinearAlgebraPurePython.py +++ b/LinearAlgebraPurePython.py @@ -327,8 +327,14 @@ def determinant_fast(A): # Section 2: Row manipulate A into an upper triangle matrix 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 + for i in range(fd+1,n): + if AM[i][fd] != 0: + temp = AM[fd] + AM[fd] = AM[i] + AM[i] = temp + break + 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. From 7cab1c8c42cb8cad15c4d3f9437f07c70890d884 Mon Sep 17 00:00:00 2001 From: RandomGamingDev <83996185+RandomGamingDev@users.noreply.github.com> Date: Fri, 24 Nov 2023 01:17:14 -0500 Subject: [PATCH 2/2] Update LinearAlgebraPurePython.py --- LinearAlgebraPurePython.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/LinearAlgebraPurePython.py b/LinearAlgebraPurePython.py index ed5c4f4..ccaf130 100644 --- a/LinearAlgebraPurePython.py +++ b/LinearAlgebraPurePython.py @@ -326,15 +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: # 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 - return 0 # If there are no other rows that can do that then return the determinant of 0 + 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. @@ -344,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