The following abs-function sometimes returns -0
(minus zero)
inline float abs(float a){
return( a>=0.0f? a :-a);
}
To be more specific, the statement sprintf(str, "%.2f", abs(-0.00f) );
produces "-0.00", and that is annoying since the string is displayed to the user.
Question:
1) Why does it produce -0
?
2) How to fix it?
PS: I am using xcode's (objective) c compiler.
The abs() function in C++ returns the absolute value of the argument. It is defined in the cmath header file. Mathematically, abs(num) = |num| .
Perl | abs() function Returns: Function returns the absolute value of the arguments passed.
Abs() Function : In MS Access, the abs() function returns a positive (absolute) number. In this function, either a positive number or a negative number is passed, and it returns the absolute of that number. It takes a number as a parameter and it returns the positive value of that number.
Because -0.0 == 0.0
and thus -0.0 >= 0.0
is true.
Use fabs
(or fabsf
for float instead of double
) rather than trying to reinvent it.
-0 is an artifact of binary representation, 0 with the sign bit set. Wikipedia has a comprehensive article on signed zero if you would like further details.
Use fabs() as people have said above. If you really really really want to inline, chain your compares:
inline float abs(float a) { return (a > 0.f) ? a : ( (a < 0.f) ? -a : 0); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With