-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtorque.py
114 lines (83 loc) · 2.51 KB
/
torque.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# import decimal
from fractions import Fraction
def echelon(mat):
# mat = [[0, 3, 0, -1], [5, 2, -8, 8], [-4, 5, 9, -9]]
pi = 0
pj = 0
columns = len(mat[pi])
rows = len(mat)
# mat = [[decimal.Decimal(x) for x in row] for row in mat]
while True:
flag = False
for i in range(len(mat)):
if mat[i][pj] == 0:
flag = True
continue
elif flag is True:
# swap current row with pivot row
mat[i], mat[pi] = mat[pi], mat[i]
break
else:
break
# scale the pivot to one:
try:
mat[pi] = [Fraction(i, mat[pi][pi]) for i in mat[pi]]
except ZeroDivisionError as e:
print(e)
# turn everything under pivot to 0
for x in range(1, rows):
if pi + x < rows:
if mat[pi + x][pj] == 0:
continue
else:
multiplier = mat[pi + x][pj]
mat[pi + x] = [mat[pi + x][i] - Fraction(mat[pi][i], Fraction(1, multiplier)) for i in
range(columns)]
pi += 1
pj += 1
# print (mat, f"\n")
if pi >= rows or pj >= columns:
return mat # returned mat
return mat
# decimal.setcontext(decimal.Context(prec=3))
mat = [[1, -1, 2, 8], [0, 0, 7, 50], [0, 0, 10, 24]]
temp = echelon(mat)
def rref(mat):
rows = len(mat)
cols = len(mat[0])
check = False
for i in mat[-1]:
if i != 0:
check = True
break
if check:
pi = -1
pj = -2
else:
pi = -2
pj = -2
while pi >= -rows:
i = 1
while i < rows:
try:
if mat[pi-i][pj] != 0:
multiplier = mat[pi-i][pj]
mat[pi-i][-1] = mat[pi-i][-1] - (multiplier * mat[pi][-1])
mat[pi-i][pj] = 0
i += 1
except IndexError as e:
break
pi -= 1
pj -= 1
check_output(mat)
return mat
def check_output(mat):
for row in mat:
temp = 0
for c in range(0, len(row) - 1):
temp += row[c]
if temp == 0 and row[-1] != 0:
raise Exception("no solution for the given matrix")
temp = rref(temp)
print(f"{temp[0]}\n{temp[1]}\n{temp[2]}")
print(check_output(temp))