Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from math import *
- # Change this matrix here to get a new determinant; make sure it's square!
- input_matrix = [ [3,4,5], [5,12,13], [1,0,-1] ]
- # The determinant of a matrix is only applicable to a square matrix; thus, the given_matrix array must be representative of a square matrix.
- # The given_matrix array should contain arrays, each of which represent one row of a square matrix.
- # Thus, there should be as many elements in each of those arrays as there are arrays.
- ######## I would actually like to note:
- # I made this script on an assumption of a recursive pattern existing to find the determinant of any-dimension matrix.
- # I am not claiming it holds, mathematically, because I don't actually know if it does!
- # This was not so much a project to build a tool for solving a matrix, but a test for my ability to make a recursive function.
- # (Also, it seems to run out of steam if you give it a matrix that's too big and I don't know how to get around that)
- ######## Thank you.
- def find_determinant( given_matrix ):
- print("function running on given_matrix: " + str(given_matrix))
- #error checking first!
- for i in given_matrix:
- #making sure all of the elements of the array are also arrays
- # if not isinstance(i, list):
- # print(str(i) + " not an array")
- # return null ### TO-DO: should try to get this error-check working for the data type of given_matrix at some point, but I'm tired.
- #making sure the matrix is a square
- if len(i) != len(given_matrix):
- print(str(given_matrix) + " not a square matrix")
- return null
- matrix_size = len(given_matrix[0]) #finds the size of the matrix; the goal is to recursively reduce to 2x2 matrices and find their determinants
- if matrix_size == 2:
- return ( (given_matrix[0][0] * given_matrix[1][1]) - (given_matrix[0][1] * given_matrix[1][0]) ) #det(A) = ad-bc
- determinant = 0.0
- terms = []
- matrix_of_minors = []
- for n in range(matrix_size):
- terms.append( given_matrix[0][n] * pow(-1,n) ) #establishes the scalars and cofactors of our terms
- minor = []
- for i in range(matrix_size): #row
- minor_row = []
- for j in range(matrix_size): #column
- if i != 0 and j != n: minor_row.append(given_matrix[i][j])
- if len(minor_row) == matrix_size-1:
- minor.append(minor_row)
- minor_row = []
- if len(minor) == matrix_size-1:
- matrix_of_minors.append(minor)
- minor = []
- for i in range(matrix_size):
- matrix_of_minors[i] = find_determinant( matrix_of_minors[i] ) #recursion!
- for i in range(matrix_size):
- determinant += terms[i] * matrix_of_minors[i]
- #print(str(determinant))
- return determinant
- print("The determinant is: " + find_determinant(input_matrix))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement