C programming fabs , fabsf, fabsl math.h


In C programming the <math.h> fabs,fabsf and fabsl function give the absolute value of the value.The declaration of the functions are given below.

fabs

1 float fabs(float x);
2 double fabs(double x);
3 long double fabs(long double x);
4 float fabsf(float x);
3 long double fabsl(long double x);

Parameters:
x -The floating point value.

Return type
floating point -The absolute value of ‘x’.

All the functions are the same,they compute the absolute value of the argument.The 1st,2nd and the 3rd function have the same name i.e.’fabs’.The 4th and 5th function have different names.What does having a different names mean is explained in detail below.

Some points to note:

i) The fabs function is quite fast.

ii) If NAN is passed NAN is returned.

iii) If ±∞ is passed ∞ is returned.

iv) If ±0 is passed 0 is returned.

Code example

double d=-12.34 , x1=2e-200 ;

float f=-12.34 ;

long double ld=-12.34 ;

printf(“%lf”, fabs( d ) ) ; //calls the 2nd version
printf(“\n%f”, fabs( f ) ) ; //calls the 1st version
printf(“\n%Lf”, fabs( ld ) ) ;//calls the 3rd version

printf(“\n%lf”, fabs( x1 ) ) ;
printf(“\n%lf”, fabs( NAN ) ) ;

Output in Visual Studio,

12.340000
12.340000
12.340000
0.000000
inf

Note here the return value is a +ve value and of floating point type that is why the fractional value is retain.






fabsf

The ‘fabsf‘ function is same as the 1st function.This means the parameter and return type of the function is float type.The ‘f‘ character appended to ‘fabsf‘ stands for float and it signify the parameter type and return type of the function.

Code example

float x=-0.270 ;

printf(“%f”, fabs( x ) ); //Calls the 1st version
printf(“\n%f”, fabsf( -0.27000 ) ); Calls the 4th version

Output in Visual Studio,

0.270000
0.270000


fabsl

The ‘fabsl‘ function is same as the 1st function.This means the parameter and return type of the function is long double type.The ‘l‘ character appended to ‘fabsl‘ stands for long double and it signify the parameter type and return type of the function.

Code example

long double x=-0.27000 ;

printf(“%Lf”, fabs( x ) ); //Calls the 3rd version
printf(“\n%Lf”, fabsl( -0.27000 ) ); Calls the 5th version

Output,

0.270000
0.270000