Матричный метод и метод Крамера для решения СЛУ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/env python
# -*- coding: utf-8 -*-
from copy import deepcopy
a = [[2., 5., 4.],
[1., 3., 2.],
[2., 10., 9.]]
b = [[30., 150., 110.],]
def multiply(a, b):
n = len(a); m = len(a[0]); k = len(b)
c = []
for i in range(n):
c.append([])
for s in range(k):
sum = 0.
for j in range(n):
sum += a[i][j]*b[s][j]
c[len(c)-1].append(sum)
if len(c[0]) > 1:
return c
else:
cc = []
for i in range(len(c)):
cc.append(c[i][0])
return cc
def transp(a):
b = []
for i in range(len(a[0])):
x = []
for j in range(len(a)):
x.append(a[j][i])
b.append(x)
return b
def minor(a, i, j):
b = []; n = len(a)
for ii in range(n):
if ii != i:
b.append([])
for jj in range(n):
if jj != j:
b[len(b)-1].append(a[ii][jj])
return det(b)
def alg_add(a, i, j):
return minor(a, i, j) * ((-1) ** (i + j))
def inverse(a):
b = []
n = len(a)
for i in range(n):
b.append([])
for j in range(n):
b[len(b)-1].append(alg_add(a, i, j) / float(det(a)))
return transp(b)
def det(a):
n = len(a)
if n == 0 or n != len(a[0]):
return False
elif n == 2:
return a[0][0]*a[1][1] - a[0][1]*a[1][0]
else:
s = 0.
for i in range(n):
s += a[i][0]*alg_add(a, i, 0)
return s
def matrix_method(a, b):
return multiply(inverse(a), b)
def cramer_method(a, b):
n = len(a); m = len(a[0])
x = []
d = det(a)
for j in range(m):
da = deepcopy(a)
for i in range(n):
da[i][j] = b[0][i]
x.append(det(da) / d)
return x
if __name__ == "__main__":
print(matrix_method(a, b))
print(cramer_method(a, b))