Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curiously, why does my abs-function return -0?

Tags:

c

objective-c

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.

like image 503
ragnarius Avatar asked Jul 12 '13 17:07

ragnarius


People also ask

How do you find the ABS value in C++?

The abs() function in C++ returns the absolute value of the argument. It is defined in the cmath header file. Mathematically, abs(num) = |num| .

How do I get absolute value in Perl?

Perl | abs() function Returns: Function returns the absolute value of the arguments passed.

How do you do absolute value in access?

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.


2 Answers

  1. Because -0.0 == 0.0 and thus -0.0 >= 0.0 is true.

  2. Use fabs (or fabsf for float instead of double) rather than trying to reinvent it.

like image 95
R.. GitHub STOP HELPING ICE Avatar answered Oct 06 '22 23:10

R.. GitHub STOP HELPING ICE


  1. -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.

  2. 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); }

like image 44
Alex Curylo Avatar answered Oct 06 '22 21:10

Alex Curylo