[Numpy-discussion] comparing floating point numbers

David Cournapeau cournape at gmail.com
Wed Jul 21 04:46:11 EDT 2010


On Tue, Jul 20, 2010 at 3:31 AM, Ondrej Certik <ondrej at certik.cz> wrote:
> Hi,
>
> I was always using something like
>
> abs(x-y) < eps
>
> or
>
> (abs(x-y) < eps).all()
>
> but today I needed to also make sure this works for larger numbers,
> where I need to compare relative errors, so I found this:
>
> http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

Actually, there is better, as mentioned in that same page. I
implemented the functions for reliable, amplitude independent floating
point comparison:

assert_array_max_ulp:

    Given two arrays a and b, check that every item differs in at most N
    Unit in the Last Place.

assert_array_almost_equal_nulp

    Compare two arrays relatively to their spacing. It is a relatively
    robust method to compare two arrays whose amplitude is variable.

    Note
    ----
    An assertion is raised if the following condition is not met:

        abs(x - y) <= nulps * spacing(max(abs(x), abs(y)))

    Parameters
    ----------
    x: array_like
        first input array
    y: array_like
        second input array
    nulp: int
        max number of unit in the last place for tolerance (see Note)

I think we should go toward using those almost everywhere we need
floating point comparison in testing,

cheers,

David



More information about the NumPy-Discussion mailing list