Search code examples
pythonarraysunit-testingassert

Assert array almost equal zero


I'm writing unit tests for my simulation and want to check that for specific parameters the result, a numpy array, is zero. Due to calculation inaccuracies, small values are also accepted (1e-7). What is the best way to assert this array is close to 0 in all places?

  • np.testing.assert_array_almost_equal(a, np.zeros(a.shape)) and assert_allclose fail as the relative tolerance is inf (or 1 if you switch the arguments) Docu
  • I feel like np.testing.assert_array_almost_equal_nulp(a, np.zeros(a.shape)) is not precise enough as it compares the difference to the spacing, therefore it's always true for nulps >= 1 and false otherways but does not say anything about the amplitude of a Docu
  • Use of np.testing.assert_(np.all(np.absolute(a) < 1e-7)) based on this question does not give any of the detailed output, I am used to by other np.testing methods

Is there another way to test this? Maybe another testing package?


Solution

  • If you compare a numpy array with all zeros, you can use the absolute tolerance, as the relative tolerance does not make sense here:

    from numpy.testing import assert_allclose
    
    def test_zero_array():
        a = np.array([0, 1e-07, 1e-08])
        assert_allclose(a, 0, atol=1e-07)
    

    The rtol value does not matter in this case, as it is multiplied with 0 if calculating the tolerance:

    atol + rtol * abs(desired)
    

    Update: Replaced np.zeros_like(a) with the simpler scalar 0. As pointed out by @hintze, np array comparisons also work against scalars.