What does the function "fabs(_:)" do?

What does the method fabs(_:) do? There is no explanation in the documentation: https://developer.apple.com/documentation/kernel/1557277-fabs. It looks like a function to calculate absolute value, but what does the "f" stand for?

Accepted Reply

The name is a historical curiosity. In the C standard library, mathematical functions (such as sin, cos or tan) take a "double" parameter, and there are variants with a suffix that take other types (e.g. sinf for a "float" parameter, or sinl for a "long double" parameter).


In the case of the "abs" function for absolute value, when the floating point library functions were added to the specification, there was already an "abs" function that took an "int" parameter. That meant the floating point versions needed different names, so: "fabs", "fabsf" and "fabsl", with the initial "f" meaning "floating point".


This is a common gotcha in C programming, because if "myValue" is a variable of type "double" (say), and you write "double result = abs (myValue)", it looks like you are taking the absolute value, but the C compiler [correctly and automatically] converts the double to an int by truncating it, computes the absolute value of the truncated integer, converts it back to a double, and this isn't the answer you wanted.

Replies

The name is a historical curiosity. In the C standard library, mathematical functions (such as sin, cos or tan) take a "double" parameter, and there are variants with a suffix that take other types (e.g. sinf for a "float" parameter, or sinl for a "long double" parameter).


In the case of the "abs" function for absolute value, when the floating point library functions were added to the specification, there was already an "abs" function that took an "int" parameter. That meant the floating point versions needed different names, so: "fabs", "fabsf" and "fabsl", with the initial "f" meaning "floating point".


This is a common gotcha in C programming, because if "myValue" is a variable of type "double" (say), and you write "double result = abs (myValue)", it looks like you are taking the absolute value, but the C compiler [correctly and automatically] converts the double to an int by truncating it, computes the absolute value of the truncated integer, converts it back to a double, and this isn't the answer you wanted.