解N元一次线性方程组
方程组形如:
a11X1+a12X2+……a1nXn=b1
a21X1+a22X2+……a2nXn=b2
……
an1X1+an2X2+……annXn=bn
解题思路:
1、一个N元一次方程组,可以通过求系数矩阵获得方程的解。
(1)计算所有a的系数矩阵值d,如果d不为0,则方程有解,否则,方程无解。
(2)将第一列(程序中为0列)的系数a11,a21,……an1用b1、b2、……bn替代,获取该系数矩阵值d1,则X1=d1/d;以此类推,求得X2、X3、……Xn。
2、系数矩阵运用拉普拉斯展开定理逐步求得。例如,当前N×N系数矩阵可以简化为第一行(程序中为0行)每一个系数×它的余子式之和(偶+奇-),该余子式是一个(N-1)×(N-1)的系数矩阵。直到余子式是2*2的系数矩阵时,计算该系数矩阵的值(a11×a22-a21×a12)。
3、构造3个函数,分别获取余子式,计算系数矩阵值,替换矩阵。
# 获取第0行,第x列元素余子式的行列式(系数矩阵)
def get_child(x, sub):
result = []
for row in range(len(sub)):
if row == 0:
continue
temp = []
for col in range(len(sub)):
if col == x:
continue
temp.append(sub[row][col])
result.append(temp)
return result
# 运用拉普拉斯展开定理,通过递归的方式计算行列式(系数矩阵)的值
def calc(matrix):
if len(matrix) == 2:
return matrix[1][1] * matrix[0][0] - matrix[1][0] * matrix[0][1]
elif len(matrix) > 2:
result = 0
for i in range(len(matrix)):
# 获得余子式
child_item = get_child(i, matrix)
result += (matrix[0][i] * ((-1) ** i) * calc(child_item))
return result
# 替换矩阵
def replace(x, a, b):
length = len(a)
result = copy.deepcopy(a)
for i in range(length):
result[i][x] = b[i]
return result
if __name__ == "__main__":
import copy
a2 = [[3.4, 50.2],
[2.1, 0.55]]
b2 = [44.5, 5.9]
a3 = [[1, 1, 1],
[1, 2, 3],
[1, 5, 1]]
b3 = [5, 9, 10]
a4 = [[0, -7, 9, -11],
[0, -7, 7, -12],
[0, 2, -1, 2],
[1, 4, -7, 6]]
b4 = [6, 9, 10, -12]
a5 = [[1, 2, 3, 4, 5],
[2, 1, 3, 4, 5],
[7, 2, 3, 6, 5],
[1, 2, 5, 8, 1],
[5, 2, 3, 4, 5]]
b5 = [1, 2, 3, 4, 5]
ab = [[a2, b2], [a3, b3], [a4, b4], [a5, b5]]
for p in ab:
result1 = []
d = calc(p[0])
if d == 0:
print("无解!")
continue
for k in range(len(p[0])):
r = replace(k, p[0], p[1])
result1.append(calc(r) / d)
print(result1)
D:\Python\Python38\python.exe D:/Python/study/20200908/test18.py
[2.623901496861419, 0.7087397392563978]
[2.375, 1.25, 1.375]
[-6.666666666666667, 13.37037037037037, 2.1481481481481484, -7.296296296296297]
[1.0, -0.0, 3.9545454545454546, -2.0, -0.7727272727272727]
Process finished with exit code 0