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?
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.
Description. The C library function int abs(int x) returns the absolute value of int x.
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.
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));
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.
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);
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