Python math.fabs() function


The math.fabs() function in Python is used to return the absolute value of a number as a float. Unlike the built-in abs() function, which can return an integer or a float depending on the input, math.fabs() always returns a float.

Syntax

import math result = math.fabs(x)
  • x: A numeric expression (integer or float) for which you want to find the absolute value.

Return Value

  • Returns the absolute value of x as a float.

Examples

  1. Finding the absolute value of a positive number:

    import math result = math.fabs(5) print(result) # Output: 5.0
  2. Finding the absolute value of a negative number:

    result = math.fabs(-3.14) print(result) # Output: 3.14
  3. Finding the absolute value of zero: The absolute value of zero is zero.

    result = math.fabs(0) print(result) # Output: 0.0
  4. Using math.fabs() with a floating-point number:

    result = math.fabs(-2.71) print(result) # Output: 2.71
  5. Combining with other mathematical operations: You can use math.fabs() in expressions and with other functions:

    x = -4.5 result = math.sqrt(math.fabs(x)) print(result) # Output: 2.1213203435596424

Summary

  • The math.fabs() function calculates the absolute value of a number, ensuring the result is returned as a float.
  • It is useful when you specifically want a float output, regardless of whether the input is an integer or a float.
  • This function can be beneficial in mathematical calculations where negative values are involved, and you want to ensure that the output is non-negative and in floating-point format.