Python - Getting the Absolute Value

To get the absolute value, you can use the built-in function abs, the fabs function from the math module, and the fabs function from the cmath module.

How to Calculate Absolute Value

How to use the built-in function abs:
Absolute value (integer type) = abs(<integer type>)
Absolute value (floating-point type) = abs(<floating-point type>)
Absolute value (floating-point type) = abs(<complex type>)

How to use the fabs function from the math module:

import math

Absolute value (floating-point type) = math.fabs(<integer type>)
Absolute value (floating-point type) = math.fabs(<floating-point type>)

Difference between abs function and math.fabs function

math module and cmath module

The math module provides mathematical functions but does not support complex numbers. If you want to handle complex numbers, use the cmath module. However, the cmath module does not provide a function to return the absolute value. To get the absolute value of a complex number, use the abs function.

Sample Code

The following sample code calculates and displays the absolute value using the abs function.
int_p_value = 99
int_m_value = -99
float_p_value = 99.99
float_m_value = -99.99

print(abs(int_p_value))    # Result = 99
print(abs(int_m_value))    # Result = 99

print(abs(float_p_value))  # Result = 99.99
print(abs(float_m_value))  # Result = 99.99
Execution result of sample code (abs)
Execution result of sample code (abs)

The following sample code calculates and displays the absolute value using the fabs function from the math module.

import math

int_p_value = 99
int_m_value = -99
float_p_value = 99.99
float_m_value = -99.99

print(math.fabs(int_p_value))    # Result = 99.0
print(math.fabs(int_m_value))    # Result = 99.0

print(math.fabs(float_p_value))  # Result = 99.99
print(math.fabs(float_m_value))  # Result = 99.99
Execution result of sample code (math.fabs)
Execution result of sample code (math.fabs)

References

Test Environment