[Python-ideas] Way to check for floating point "closeness"?

Nathaniel Smith njs at pobox.com
Mon Jan 12 22:03:04 CET 2015


On Mon, Jan 12, 2015 at 5:02 PM, Chris Barker <chris.barker at noaa.gov> wrote:
> Now that we're talking about floating point conveniences (math.nan,
> linspace):
>
> What about putting an
>
> almost_equal(x,y,tol=1e14)
>
> (or close(), or...) in the math module.
>
> AFAICT, in the standard library, there is only:
>
> unittest.TestCase.assertAlmostEqual
>
> but it:
>
> A) is buried in the unittest.TestCase class
>
> B) is an assertion, so you can't use it as a general test (easily)
>
> C) uses number of decimal digits or an absolute delta, but does not provide
> a significant figures comparison, which is most likely what's wanted (and a
> bit harder to write yourself)
>
> numpy provides allclose() (and isclose() ), which is pretty much what I'm
> suggesting.

Unfortunately this opens a tremendous can of worms. Numpy actually provides:

allclose/assert_allclose -- absolute + relative tolerance, not symmetric

assert_approx_equal -- agreement to n digits (don't use this)

assert_array_max_ulp, assert_array_almost_equal_nulp -- tolerance
based on counting ulps. Something like a relative tolerance of n*2^-53
for doubles, but it depends on datatype bits and acts differently near
zero. I have no idea what the difference between these two functions
is.

I've recently argued that allclose should actually act slightly differently:
   http://mail.scipy.org/pipermail/numpy-discussion/2014-July/070639.html

Boost has thought about this a lot and advocates a slightly different
definition (actually, two slightly different definitions) from any of
the above:
   http://www.boost.org/doc/libs/1_34_0/libs/test/doc/components/test_tools/floating_point_comparison.html

-n

-- 
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org


More information about the Python-ideas mailing list