Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use abs() or fabs() instead of conditional negation?

In C/C++, why should one use abs() or fabs() to find the absolute value of a variable without using the following code?

int absoluteValue = value < 0 ? -value : value; 

Does it have something to do with fewer instructions at lower level?

like image 329
Subhranil Avatar asked Feb 04 '18 14:02

Subhranil


People also ask

What is the difference between math abs () and math fabs () give example?

Python | fabs() vs abs() Both will return the absolute value of a number. The difference is that math. fabs(number) will always return a floating-point number even if the argument is an integer, whereas abs() will return a floating-point or an integer depending upon the argument.

What is the use of abs function in C?

Description. The C library function int abs(int x) returns the absolute value of int x.

How is abs function implemented?

The abs () function is a predefined function in the stdlib. h header file to return the absolute value of the given integers. So, if we want to return the absolute value of a given number, we need to implement the stdlib. h header file in the C program.

What is fabs () in C?

The fabs() function takes a single argument (in double ) and returns the absolute value of that number (also in double ). [Mathematics] |x| = fabs(x) [In C programming] To find absolute value of an integer or a float, you can explicitly convert the number to double. int x = 0; double result; result = fabs(double(x));


2 Answers

The "conditional abs" you propose is not equivalent to std::abs (or fabs) for floating point numbers, see e.g.

#include <iostream> #include <cmath>  int main () {     double d = -0.0;     double a = d < 0 ? -d : d;     std::cout << d << ' ' << a << ' ' << std::abs(d); } 

output:

-0 -0 0 

Given -0.0 and 0.0 represent the same real number '0', this difference may or may not matter, depending on how the result is used. However, the abs function as specified by IEEE754 mandates the signbit of the result to be 0, which would forbid the result -0.0. I personally think anything used to calculate some "absolute value" should match this behavior.

For integers, both variants will be equivalent both in runtime and behavior. (Live example)

But as std::abs (or the fitting C equivalents) are known to be correct and easier to read, you should just always prefer those.

like image 111
Baum mit Augen Avatar answered Oct 09 '22 21:10

Baum mit Augen


The first thing that comes to mind is readability.

Compare these two lines of codes:

int x = something, y = something, z = something; // Compare int absall = (x > 0 ? x : -x) + (y > 0 ? y : -y) + (z > 0 ? z : -z); int absall = abs(x) + abs(y) + abs(z); 
like image 24
iBug Avatar answered Oct 09 '22 19:10

iBug