Detecting and adjusting for negative zero
Well, a generic suggestion when using double
s is remembering they are not exact. Thus, if equality is important - using some tolerance factor is usually advised.
In your case:
if (|r - 0.0| >= EPSILON)
where EPSILON
is your tolerance factor, will yield true if r
is not 0.0, with at least EPSILON
interval.
On some older systems (i.e. pre-IEE754) you may find equality checks against 0 fail for negative-0:
if (a == 0.0) // when a==-0.0, fails
you can work around this by adding 0.0 to a value before the comparison:
if ((a+0.0) == 0.0) // when a == -0.0, succeeds
I would caution, however, that combinations of hardware/software that really require this are quite unusual. The last time I had to do it was on a Control Data mainframe. Even there, it only arose under somewhat unusual circumstances: the Fortran compiler allowed negative zeros to be generated, and knew to compensate for them in comparisons. The Pascal compiler generated code to turn negative zeros into normal zeros as part of a computation.
Therefore, if you wrote a routine in Fortran and called it from Pascal, you could run into this problem, and prevent it as above by adding 0.0 before doing a comparison.
I'm gonna put pretty good odds that your problem doesn't really stem from comparisons with negative zero though. All reasonably modern hardware of which I'm aware handles this entirely automatically, so software never has to consider it at all.