Comparing Numpy Float Arrays In Unit Tests
Solution 1:
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.
Solution 2:
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.
Solution 3:
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.
Post a Comment for "Comparing Numpy Float Arrays In Unit Tests"