How to remove "negative zero" in c/c++? I am trying this-
#define isEq(a, b) ((abs(a-b)<EPS) ? 1 : 0)
#define NegZero(x) (x = isEq(x, -0.0) ? 0 : x)
Is it okay and safe? or is there any other easy and safe way? Specially for contest coding. please help....
With the code you posted in your comments, your approach seems correct: your answer is a negative number that is very close to zero, and because you're rounding it to three digits (using printf("... %.3lf ...", ...)
), it looks like -0.000
. Your approach (check if it's close to 0.0
using abs(a - b) < epsilon
; if it is, use 0.0
, otherwise use the value itself) is mostly correct, except for the issue that macros aren't exactly a good fit.
Rather than writing
printf("(%.3lf,%.3lf)\n", I1.x, I1.y);
I would suggest using something like
printf(
"(%.3lf,%.3lf)\n",
NegZero(I1.x),
NegZero(I1.y)
);
and define (although I'd pick different names)
static inline bool isEq(double x, double y) {
return abs(x, y) < EPS;
}
static inline NegZero(double x) {
if (isEq(x, 0.0)) {
return 0.0;
} else {
return x;
}
}
(The reason for the confused comments is that there actually is something called negative zero in IEEE floating point arithmetic. If that were the case, the suggested solutions would have worked.)