askvity

What is the Python math function for absolute value?

Published in Python Math Functions 2 mins read

The built-in Python function for finding the absolute value of a number is abs().

The abs() function is a fundamental part of Python and doesn't require importing any additional modules like the math module to use it. It's readily available for use in your Python programs.

How to Use the abs() Function

The abs() function takes a single numerical argument (integer, floating-point number, etc.) and returns its absolute value. The absolute value is the non-negative magnitude of a number, disregarding its sign.

Examples:

number1 = -10
absolute_value1 = abs(number1)
print(absolute_value1)  # Output: 10

number2 = 5.5
absolute_value2 = abs(number2)
print(absolute_value2)  # Output: 5.5

number3 = 0
absolute_value3 = abs(number3)
print(absolute_value3)  # Output: 0

As demonstrated in the examples:

  • For negative numbers, abs() returns the positive equivalent.
  • For positive numbers, abs() returns the number itself.
  • For zero, abs() returns zero.

Why Use abs() and Not math.fabs()?

While the math module does contain math.fabs(), which also calculates the absolute value, abs() is generally preferred for several reasons:

  • abs() is a built-in function, so it's always available without needing to import the math module.
  • abs() can handle integer, floating-point, and complex numbers, while math.fabs() always returns a float.
  • abs() is often considered more Pythonic and readable due to its simplicity and wide availability.

In summary, abs() is the standard and generally recommended Python function for calculating absolute values.

Related Articles