前言
基本思路
通过降阶的思想不断将行列式转为低阶行列式(递归),当阶数为2时直接计算即可
代码实现
import numpy as np
from fractions import Fraction
import sympy as sy
# index: 起始元素下标
def HLS(data: np.array, index: int):
m, flag = len(data), 0 # flag统计交换行的次数,对结果添加相应的符号
data = data.astype('object') # 将元素转为object,方便运算的进行
if m == 2:
value = data[0][0] * data[1][1] - data[0][1] * data[1][0]
return value
else:
# 寻找首个元素不为0的行并交换
if data[index][index] == 0:
count = index
while data[count][index] == 0:
count += 1
# 交换两行
data[[index, count], :] = data[[count, index], :]
flag += 1
for i in range(index, m - 1):
if data[i + 1][index] != 0:
# 使用分数表示,防止因浮点数导致结果误差
ratio = Fraction(data[i + 1][index], data[index][index])
for j in range(index, m):
# 使用sympy包的Rational()函数实现分数的友好显示
data[i + 1][j] = sy.Rational(Fraction(data[i + 1][j], 1) - Fraction(data[index][j], 1) * ratio)
intial_ele = data[index][index] # 记录起始元素,结果用
data = np.delete(data, index, axis=0) # 除去首元素所在行列
data = np.delete(data, index, axis=1)
return pow(-1, flag) * intial_ele * HLS(data, index)
if __name__ == '__main__':
data = np.array([
[1,0,0,2,0],
[3,1,4,5,0],
[6,0,1,7,0],
[0,0,0,1,0],
[8,9,10,11,1],
])
value = HLS(data, 0)
print("行列式的值为: ", value)
结果验证