-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod.py
More file actions
102 lines (91 loc) · 2.86 KB
/
method.py
File metadata and controls
102 lines (91 loc) · 2.86 KB
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
'''
matrix methods
'''
from .matrix import Matrix
def diagDiff(mat):
num1 = num2 = 1
for i in range(mat.column):
num1 *= mat.data[i][i]
num2 *= mat.data[i][mat.column - 1 - i]
return num1 - num2
'''
finding the determinant of a matix
'''
def det(mat):
if type(mat) != Matrix:
raise TypeError('this is not of type matix')
else:
if mat.rows != mat.column:
raise ValueError('cannot find the determinant of a non square matrix')
else:
if mat.column == 2:
return diagDiff(mat)
ans = diagDiff(mat)
for i in range(1, mat.column):
ans += diagDiff(mat.columnShiftLeft(i))
return ans
'''
to find the minor of an elemnt
'''
def minor(mat,coord):
if type(mat) != Matrix:
raise TypeError('this is not of type matix')
elif type(coord) != tuple and type(coord) != list:
raise TypeError(f'{coord} is not of type list o tuple')
else:
mat2 = mat.remRow(coord[0])
mat2 = mat2.remColumn(coord[1])
return mat2
'''
to find the cofactor of the matix
'''
def cofactor(mat,coord):
if type(mat) != Matrix:
raise TypeError('this is not of type matix')
elif type(coord) != tuple and type(coord) != list:
raise TypeError(f'{coord} is not of type list o tuple')
else:
mat2 = minor(mat,coord)
if (coord[0] % 2 == 1 and coord[1] % 2 == 1) or (coord[0] % 2 == 0 and coord[1] % 2 == 0):
return det(mat2)
else:
return -det(mat2)
'''
to find the transpose of the matrix
'''
def transpose(mat):
if type(mat) != Matrix:
raise TypeError('this is not of type matrix')
else:
mat2 = Matrix(mat.column, mat.rows)
for i in range(mat2.rows):
for j in range(mat2.column):
mat2.addElement(mat.data[j][i], i+1, j+1)
return mat2
'''
to find the adjoint of a matix
'''
def adjoint(mat):
if type(mat) != Matrix:
raise TypeError('this is not of type matrix')
else:
if mat.column == 2:
mat2 = Matrix(2,2)
mat2.addElement(mat.data[0][0], 2,2)
mat2.addElement(mat.data[1][1], 1,1)
mat2.addElement(-mat.data[0][1], 1, 2)
mat2.addElement(-mat.data[1][0], 2, 1)
return mat2
mat2 = Matrix(mat.rows, mat.column)
for i in range(mat.rows):
for j in range(mat.column):
mat2.addElement(cofactor(mat,(i+1, j+1)), i+1, j+1)
return transpose(mat2)
'''
to find the inverse of the matrix
'''
def inverse(mat):
if type(mat) != Matrix:
raise TypeError('this is not of type matrix')
else:
return (1/det(mat)) * adjoint(mat)