Created
November 3, 2010 18:42
-
-
Save unixpickle/661492 to your computer and use it in GitHub Desktop.
Find the determinant of any 3x3 matrix.
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 determineMatrix (matrix): | |
# here we do some major if statements | |
n1 = 0.0 | |
n2 = 0.0 | |
size = len(matrix) | |
if len(matrix[0]) != size: | |
print "Bad matrix for determination. (" + str(len(matrix)) + "x" + str(len(matrix[0])) + ") " | |
return 0.0 | |
else: | |
print "determining matrix (" + str(len(matrix)) + "x" + str(len(matrix[0])) + ") " | |
# first step here | |
for j in range(size): | |
n3 = 1 | |
for i in range(size): | |
n = matrixGetNumber(matrix, i, i + j) | |
n3 *= n | |
n1 += n3 | |
# second step here | |
for j in range(size): | |
n3 = 1 | |
for i in range(size): | |
t = (size - 1) - i | |
n = matrixGetNumber(matrix, t, i + j) | |
n3 *= n | |
n2 += n3 | |
return (n1 - n2) | |
def createMatrix (width, height): | |
matrix = list() | |
for i in range(height): | |
l = list() | |
for j in range(width): | |
l.append(0) | |
matrix.append(l) | |
return matrix | |
def matrixGetNumber (matrix, row, column): | |
return matrix[row % len(matrix)][column % len(matrix[0])] | |
def matrixSetNumber (matrix, row, column, value): | |
matrix[row % len(matrix)][column % len(matrix[0])] = value | |
def readMatrix (): | |
matrix = list() | |
for i in range(3): | |
l = list() | |
ms = "" | |
print "3x3, enter row " + str(i + 1) | |
mstr = raw_input() | |
for c in range(len(mstr) + 1): | |
mc = '' | |
if c == len(mstr): | |
mc = ' ' | |
else: mc = mstr[c:c+1] | |
if mc == ' ' or mc == '\t' or mc == '\n': | |
l.append(int(ms)) | |
# print "Append " + ms | |
ms = "" | |
else: | |
ms = ms + mc | |
matrix.append(l) | |
return matrix | |
matrix = readMatrix() | |
print "det(matrix) = " + str(determineMatrix(matrix)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment