def passed_test(dtype, as_matrix, x_is_row, stride): """ Run 2-norm computation test. Arguments: dtype: either 'float64' or 'float32', the NumPy dtype to test as_matrix: True to test a NumPy matrix, False to test a NumPy ndarray x_is_row: True to test a row vector as parameter x, False to test a column vector stride: stride of x and y to test; if None, a random stride is assigned Returns: True if the expected result is within the margin of error of the actual result, False otherwise. """ # generate random sizes for vector dimensions and vector stride (if necessary) length = randint(N_MIN, N_MAX) stride = randint(N_MIN, STRIDE_MAX) if stride is None else stride # create random vector to test x = random_vector(length, x_is_row, dtype, as_matrix) # create view of x that can be used to calculate the expected result x_2 = x.T if x_is_row else x # compute the expected result if stride == 1: expected = norm(x) else: expected = 0 for i in range(0, length, stride): expected += abs(x_2[i, 0]) ** 2 expected **= 0.5 # get the actual result actual = nrm2(x, stride) # compare the actual result to the expected result and return result of the test return abs(actual - expected) / expected < EPSILON
def test_float64_dtype(self): x = array([[1., 2., 3., 3., 1., 1.]], dtype='float64') self.assertEqual(x.dtype, 'float64') self.assertEqual(nrm2(x), 5)
def test_stride_greater_than_length(self): x = array([[1., -2., 3., 3., -1., 1.]]) self.assertEqual(nrm2(x, inc_x=6), 1)
def test_stride_less_than_length(self): x = array([[1., 2., 2., 3., 2., 1.]]) self.assertEqual(nrm2(x, inc_x=2), 3)
def test_vector_as_matrix(self): x = asmatrix(array([[1.], [2.], [3.], [3.], [1.], [1.]])) self.assertEqual(nrm2(x), 5)
def test_column_vector_as_ndarray(self): x = array([[1.], [2.], [3.], [3.], [1.], [1.]]) self.assertEqual(nrm2(x), 5)
def test_negative_element(self): x = array([[1., -2., 3., 3., -1., 1.]]) self.assertEqual(nrm2(x), 5)
def test_row_vector_as_ndarray(self): x = array([[1., 2., 3., 3., 1., 1.]]) self.assertEqual(nrm2(x), 5)
def test_scalar_as_ndarray(self): x = array([[1.]]) self.assertEqual(nrm2(x), 1)