[Numpy-discussion] comparing floating point numbers

Ondrej Certik ondrej@certik...
Mon Jul 19 20:31:00 CDT 2010


I was always using something like

abs(x-y) < eps


(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:


and wrote this:

def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
    a = float(a)
    b = float(b)
    # if the numbers are close enough (absolutely), then they are equal
    if abs(a-b) < max_absolute_error:
        return True
    # if not, they can still be equal if their relative error is small
    if abs(b) > abs(a):
        relative_error = abs((a-b)/b)
        relative_error = abs((a-b)/a)
    return relative_error <= max_relative_error

Is there any function in numpy, that implements this? Or maybe even
the better, integer based version, as referenced in the link above?

I need this in tests, where I calculate something on some mesh, then
compare to the correct solution projected on some other mesh, so I
have to deal with accuracy issues.


More information about the NumPy-Discussion mailing list