C library - fabs() function



The C math library fabs() function accepts the parameter(x) of type double that returns the absolute value of x. This function is defined under the header <math.h> that calculates the absolute value of a float point number.

Syntax

Following is the syntax of the C library fabs() function −

double fabs(double x)

Parameters

This function accepts only a single parameter −

  • x − This is the floating point value.

Return Value

This function returns the absolute value of x.

Example

Following is the C library program to see the illustration of fabs() function.

#include <stdio.h>
#include <math.h>

int main () {
   int a, b;
   a = 1234;
   b = -344;
  
   printf("The absolute value of %d is %lf\n", a, fabs(a));
   printf("The absolute value of %d is %lf\n", b, fabs(b));
   
   return(0);
}

Output

The above code produces the following result −

The absolute value of 1234 is 1234.000000
The absolute value of -344 is 344.000000

Example

Below the program calculate absolute value of floating-point numbers. Here, we have two types of absolute value − positive and negative, and when these value are passes to the function fabs(), it display the result.

#include <stdio.h>
#include <math.h>

int main() {
   double a = 9801.0;
   double b = -1831.0;
   double res;

   res = fabs(a);
   printf("The absolute value of %.3lf is %.3lf\n", a, res);

   res = fabs(b);
   printf("The absolute value of %.3lf is %.3lf\n", b, res);

   return 0;
}

Output

On execution of above code, we get the following result −

The absolute value of 980.000 is 980.000
The absolute value of -1231.000 is 1231.000

Example

Here, we calculate the approximate absolute value of long double numbers. The result of approximate number can be identify using the formula tanh = (1.0 + tanh(x / 2.0)) * (1.0 - tanh(x / 2.0).

#include <stdio.h>
#include <math.h>

long double my_exp(long double x) {
    return (1.0 + tanh(x / 2.0)) * (1.0 - tanh(x / 2.0));
}

int main() {
   long double a = -6.546;
   long double b = 5.980;
   double res;

   res = fabs(a);
   printf("The absolute value of %.3Lf is %.3lf\n", a, res);

   res = fabs(b);
   printf("The absolute value of %.3Lf is %.3lf\n", b, res);

   return 0;
}

Output

After executing the above code, we get the following result −

The absolute value of -6.546 is 6.546
The absolute value of 5.980 is 5.980
Advertisements