You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.0 KiB

def zeroes(n, m):
result = []
# iterate through rows of X
for i in range(n):
a = []
# iterate through columns of Y
for j in range(m):
a.append(0.0)
result.append(a)
return result
def diag(value, n):
ret = []
for i in range(n):
a = []
for j in range(n):
if i == j:
a.append(float(value))
else:
a.append(0.0)
ret.append(a)
return ret
# Matrix multiplication
def mm(X, Y):
result = zeroes(len(X), len(Y[0]))
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result
# Matrix addition
def ma(X, Y):
result = []
for i in range(len(X)):
temp_row = []
for j in range(len(X[i])):
temp_row.append(X[i][j] + Y[i][j])
result.append(temp_row)
return result
def m_delta(X,Y):
diff = []
for i in range(len(X)):
for j in range(len(X[0])):
diff.append(X[i][j] - Y[i][j])
return abs(sum(diff) / len(diff))
def asstet_matrix(a, b):
if len(a) == len(b):
for i in range(len(a)):
if len(a[i]) == len(b[i]):
for j in range(len(a)):
if a[i][j] != b[i][j]:
raise Exception("Assertion error!\n{}\n{}".format(a,b))
else:
raise Exception("Assertion error!\n{}\n{}".format(a,b))
else:
raise Exception("Assertion error!\n{}\n{}".format(a,b))
def test_mm():
a = [[1, 2, 3], [4, 5, 6]]
b = [[7, 8], [9, 10], [11, 12]]
result = mm(a, b)
ref = [[58, 64], [139, 154]]
asstet_matrix(result, ref)
print("test_mm: passed")
def test_ma():
a = [[3, 4], [2, 1]]
b = [[1, 5],[3, 7]]
result = ma(a, b)
ref = [[4, 9], [5, 8]]
asstet_matrix(result, ref)
print("test_ma: passed")
if __name__ == "__main__":
test_mm()
test_ma()