Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use fabs and when is it sufficient to use std::abs?

Tags:

c++

math.h

cmath

I assume that abs and fabs are behaving different when using math.h. But when I use just cmath and std::abs, do I have to use std::fabs or fabs? Or isn't this defined?

like image 338
math Avatar asked Jun 25 '10 13:06

math


People also ask

What is ABS and fabs in C?

Basically, both is used to get the absolute value of the given value. abs() is used for Integer values whereas fabs() is used for floating type data.

Where is fabs defined?

The fabs() function in C++ returns the absolute value of the argument. It is defined in the cmath header file.


2 Answers

In C++, it's always sufficient to use std::abs; it's overloaded for all the numerical types.

In C, abs only works on integers, and you need fabs for floating point values. These are available in C++ (along with all of the C library), but there's no need to use them.

like image 123
Mike Seymour Avatar answered Oct 02 '22 15:10

Mike Seymour


It's still okay to use fabs for double and float arguments. I prefer this because it ensures that if I accidentally strip the std:: off the abs, that the behavior remains the same for floating point inputs.

I just spent 10 minutes debugging this very problem, due to my own mistake of using abs instead of std::abs. I assumed that the using namespace std;would infer std::abs but it did not, and instead was using the C version.

Anyway, I believe it's good to use fabs instead of abs for floating-point inputs as a way of documenting your intention clearly.

like image 40
Alan Turing Avatar answered Oct 02 '22 16:10

Alan Turing