Floating point comparisons in Python xarray
Like the Numpy helper function numpy.testing.assert_allclose(), the Xarray helper function xarray.testing module compares floating point arrays within a specified tolerance. Example:
import xarray
import xarray.testing
# code under test
dat = myfunc(...)
# load the reference Dataset to compare against
ref = xarray.open_dataset("ref.nc")
xarray.testing.assert_allclose(ref, dat)
dat.equals(ref) is generally inappropriate to directly compare floating point numbers. Clive Moler’s article address the topic of floating point comparisons succinctly.
Floating point comparison algorithm: across computing languages, an algorithm suitable for comparing floating point numbers “actual, desired” to absolute tolerance “atol” and relative tolerance “rtol” is:
isclose = abs(actual - desired) <= max(rtol * max(abs(actual), abs(desired)), atol)
isclose
is boolean True or False – an array if actual
or desired
are arrays.