14

What is the best way to implement a unittest that compares two numpy float arrays.

I've tried unittest.assertEqual() but didn't work for float arrays because float are never 100% equal. I can't use assertAlmostEqual because it tests the round(floats) equality ...

does anyone emplemented something like this

self.assertFloatArrayEqual(array1, array2, msg = "array are not equal")

thanks

4
  • Not sure if this will help you, but for comparing floats have you tried something like the is keyword? Commented Feb 17, 2013 at 12:02
  • The answer to my question Compare (assert equality of) two complex data structures containing numpy arrays in unittest could work for you (may not really be a duplicate though). Commented Feb 17, 2013 at 12:03
  • Using "is" is not comparing for approximate equality like requested but comparing for identity. Equality and identity are two very different beasts! Commented Feb 17, 2013 at 12:05
  • Please put some attention into writing your question title. What you had had vanishingly small quantity of meaning. If you're specific, people are much more likely to look. Commented Feb 17, 2013 at 12:28

3 Answers 3

31

If you are using numpy anyway, why not use the numpy testing functions?

numpy.testing.assert_array_almost_equal

and

numpy.testing.assert_array_almost_equal_nulp

These also handles NaN's fine, check shape, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

The benefit of this approach over self.assertTrue(numpy.allclose...) is that you get a very helpful exception showing the actual values of the arrays.
8

Try

self.assertTrue(numpy.allclose(array1, array2, rtol=1e-05, atol=1e-08))

The allclose function from the numpy module, checks whether two arrays are the same within machine precision a given relative and absolute tolerance . rtol and atol are optional parameters with default values as given above.

Thanks to @DSM for correcting me.

2 Comments

"within machine precision": I hope you're not writing code assuming that! The default tolerances are rtol=1.e-5, atol=1.e-8 in my version, and that's nowhere close to machine precision.
While I think that the unittest variant for array comparisons provides nicer output when differences are found, this is still far better than rolling one's own.
1

There is a version that can compare two arrays, which of course requires that numpy arrays behave properly, i.e. that they have a len() and that they allow square brackets to access elements. Now, concerning rounding errors, there is the possibility to define a delta or a range, which you could use, but I don't think this allows the use on arrays.

I'm afraid you'll have to roll your own.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.