I'm pretty sure 0.0 always equals -0.0. I think it's part of the c
specification. Now, on OpenBSD, you can't print -0.0, as it will print
0.0 instead which is really annoying. This is with at least 3.8 but I
don't know if it's been changed since then. Anyway, to test for -0.0
instead of 0.0, you have to use copysign.
Anyway, comparing equality of floats is never accurate, since the
floats themselves are inaccurate.
On Aug 1, 2007, at 3:50 PM, Joshua Hoblitt wrote:
I'm not sure if 0.0 == -0.0 is true on all platforms. It should be for
IEEE754 compliance but in the real world...
It might be nice to throw in a few tests to see if the example code
below would have the same results on all platforms.
--
#include <stdio.h>
#include <math.h>
int main ()
{
printf("0.0 : %f\n", 0.0);
printf("-0.0 : %f\n", -0.0);
printf("0.0 == -0.0 : %d\n", 0.0 == -0.0);
}
--
-J
--
On Wed, Aug 01, 2007 at 08:38:15AM +0200, Paul Cochrane wrote:
A couple of comments on dealing with floats.
- Use FLT_EPSILON/DBL_EPSILON from float.h
- You method is total overkill, return (fabs(x - y) < DBL_EPSILON ?
1 : 0);
should be sufficent (note: check with a numerical expert).
This is what I thought in the beginning. However, whether one uses
FLT_EPSILON or DBL_EPSILON depends upon the type of the numbers used
(float or double), so there wasn't a nice general solution. Anyway, I
thought it best to ask on list before I started implementing stuff.
:-)
- What about NANs and INFs? I typical test for one of the values
being
NAN but allow INFs to be compared.
Andy Lester's post mentioned that we're only comparing against zero in
each instance so we don't really need the general solution and so
shouldn't need to worry about this case.
Paul