線性代數程式題 - 計算出四階的行列式值 (Determinant)
假設求解:
輸入範例: 1 -2 3 0 -1 1 0 2 0 2 0 3 3 4 0 -2
輸出範例: 39.000
# Python 線性代數 determinant 4 階
# Input: 將所有數字放在一整行
# Output: 一個浮點數至小數點後第三位
def input_m(num):
matrix = []
input_raw = input().split()
for i in range(num):
matrix_row = []
for j in range(num):
matrix_row.append(float(input_raw[i * (num) + j]))
matrix.append(matrix_row)
return matrix
def output_m(num, matrix):
for i in range(num):
for j in range(num):
if j != 0:
print(' ', end='')
print(matrix[i][j], end='')
print('')
def det_2(m):
return m[0][0] * m[1][1] - m[0][1] * m[1][0]
def det_3(m):
m_1 = [[m[1][1], m[1][2]], [m[2][1], m[2][2]]]
m_2 = [[m[1][0], m[1][2]], [m[2][0], m[2][2]]]
m_3 = [[m[1][0], m[1][1]], [m[2][0], m[2][1]]]
return m[0][0] * det_2(m_1) - m[0][1] * det_2(m_2) + m[0][2] * det_2(m_3)
def det_4(m):
m_1 = [[m[1][1], m[1][2], m[1][3]], [m[2][1], m[2][2], m[2][3]], [m[3][1], m[3][2], m[3][3]]]
m_2 = [[m[1][0], m[1][2], m[1][3]], [m[2][0], m[2][2], m[2][3]], [m[3][0], m[3][2], m[3][3]]]
m_3 = [[m[1][0], m[1][1], m[1][3]], [m[2][0], m[2][1], m[2][3]], [m[3][0], m[3][1], m[3][3]]]
m_4 = [[m[1][0], m[1][1], m[1][2]], [m[2][0], m[2][1], m[2][2]], [m[3][0], m[3][1], m[3][2]]]
return m[0][0] * det_3(m_1) - m[0][1] * det_3(m_2) + m[0][2] * det_3(m_3) - m[0][3] * det_3(m_4)
def main():
num = 4
matrix = input_m(num)
output_m(num, matrix)
ans = det_4(matrix)
print('%.3f' % (ans))
if __name__ == '__main__':
main()