I have defined the following function in Python to return a normalized version of the matrix M.
def get_normalized_matrix(M, O):
M_copy = np.copy(M)
M_copy[O == 0] = 0
a = np.sum(M_copy) / np.sum(O)
s = np.sqrt(np.sum((M_copy - a)**2) / np.sum(O))
M_normalized = (M_copy - a) / s
return M_normalized
After running the following check, I get an AssertionError for assert(abs(np.sum(Mn**2 * O) / np.sum(O) - 1) < 1e-6).
def check_normalization():
M = np.random.rand(10, 3)
O = (np.random.rand(10, 3) > 0.5) + 0
Mn = get_normalized_matrix(M, O)
assert(abs(np.sum(M * O)) > 1e-6)
assert(abs(np.sum(Mn * O)) < 1e-6)
assert(abs(np.sum(Mn**2 * O) / np.sum(O) - 1) < 1e-6)
print("Function {} is working fine!".format('get_normalized_matrix'))
check_normalization()
Can you help me figure out where I went wrong and how I can fix this?
assert(abs(np.sum(Mn**2 * O) / (np.sum(O) - 1)) < 1e-6)instead ofassert(abs(np.sum(Mn**2 * O) / np.sum(O) - 1) < 1e-6)? Moreover, the assertion error occurs because the value returned fromabs(np.sum(Mn**2 * O) / np.sum(O) - 1)is less than1e-6.