该函数可以精确计算1x1,2x2和3x3行列式,但它为高阶行列式提供了错误的值。我认为函数中的部分存在问题,我将函数(递归)作为解决方案的一部分来解决低阶决定因素。
我怀疑它与变量局部性有关,但我不确定为什么会出现问题,因为我认为局部性是自动的。
顺便说一下,这是Python 2。
代码:
def is_Det(matrix):
isdet = True
if not isinstance(matrix,list): # Is this actually a list?
isdet = False
for i in matrix:
if isinstance(i,list): # Things in matrix are lists?
if len(i) == len(matrix): # Square shape?
for j in i: # All numbers?
try:
j = float(j)
except ValueError:
isdet = False
else:
isdet = False
else:
isdet = False
return isdet
def det_Disp(matrix):
if is_Det(matrix):
pass
else:
print "Error: Input not a determinant, cannot display"
def det_Eval(matrix):
print matrix
except StandardError:
print "No such value"
if is_Det(matrix):
if len(matrix) == 1: # 1x1 determinant
print matrix[0][0]
return matrix[0][0]
elif len(matrix) == 2: # 2x2 determinant
print matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
else:
longdet = matrix # Expands higher-order determinant
for row1 in longdet:
for col1 in range(0,len(matrix)-1):
row1.append(row1[col1])
value = 0
for col2 in range(0,len(matrix)): # Recurse determinant value
subdet = []
for row2 in range(1,len(matrix)):
subsubdet = []
for col3 in range(col2+1,col2+len(matrix)):
subsubdet.append(longdet[row2][col3])
'''print "Subsubdet:",
print subsubdet #***************************'''
subdet.append(subsubdet)
'''# print "Subdet",
print "Subdet:",
print subdet #***************************'''
value += longdet[0][col2] * det_Eval(subdet)
##########print value
'''#print longdet[1][col2],
#print det_Eval(subdet),
#print value
# print longdet'''
return value
else:
print "Error: Input not a determinant, cannot evaluate"
#print det_Eval([[2,3],[4,9]])
#print det_Eval([[6,1,8],[9,9,9],[9,7,4]])
print det_Eval([[8,9,2,3],[4,6,1,8],[9,9,9,9],[1,9,7,4]])
答案 0 :(得分:2)
In this line dealing with minors:
value += longdet[0][col2] * det_Eval(subdet)
you don't take sign into account - sign depends on parity of index of the first line element (col2)