[Numpy-discussion] comparing floating point numbers
Ondrej Certik
ondrej@certik...
Mon Jul 19 20:31:00 CDT 2010
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
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)
else:
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.
Ondrej
More information about the NumPy-Discussion
mailing list