Created
June 16, 2021 15:20
-
-
Save ialexpovad/ec42f159095563322c2ea7d73ed2ed1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def determinant(A, output=0): | |
''' | |
The function return determinant of a square matrix using full recursion. | |
output=0 - etablish a output at each recursion level. | |
''' | |
# Store indices in list for row referencing | |
index=list(range(len(A))) | |
# If at 2 x 2 submatrices recursive calls end | |
if len(A)==2 and len(A[0])==2: | |
det=A[0][0]*A[1][1] - A[0][1]*A[1][0] | |
return det | |
# Define submatrix for focus column and call this function | |
for focuscolumn in index: | |
addA=A | |
addA=addA[1:] | |
height=len(addA) | |
for item in range(height): | |
addA[item]=addA[item][0:focuscolumn]+addA[item][focuscolumn+1:] | |
sign=(-1)**(focuscolumn % 2) | |
subDeterminant=determinant(addA) | |
# Output: all from recursion | |
output=output+sign*A[0][focuscolumn]*subDeterminant | |
return output | |
def det(A): | |
''' | |
Create an upper triangle matrix using row operations. | |
Then product of diagonal elements is the determinant. | |
''' | |
# Establish n parametr size matrix A | |
# additional A | |
n=len(A) | |
addA=A | |
# Rows ops on A to get in upper triangle form | |
for focusDiagonal in range(n): | |
# If diagonal is zero components | |
if addA[focusDiagonal][focusDiagonal]==0: | |
# change to approx zero | |
addA[focusDiagonal][focusDiagonal]=1.0e-16 | |
for i in range(focusDiagonal+1,n): | |
# Current row | |
numberCurrentRow=addA[i][focusDiagonal]/addA[focusDiagonal][focusDiagonal] | |
for j in range(n): | |
addA[i][j]=addA[i][j]-numberCurrentRow*addA[focusDiagonal][j] | |
# Once additional A is in upper triangle form product of diagonals is determinant | |
product=1.000 | |
for i in range(n): | |
product=product*addA[i][i] | |
return product | |
if __name__=="__main__": | |
None | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment