PythonBuilt-in functions
abs()
Returns the absolute value of a number.
- Returns
- The absolute value.
Example
#Python
print(abs(-7), abs(7))
target = 100
results = [96, 108, 99]
print([abs(r - target) for r in results])
print(abs(3 + 4j))Resultsaved result, you can check it
7 7
[4, 8, 1]
5.0
Definition and usage
#The abs() function returns a number without its minus sign, that is, its distance from zero. abs(-7) and abs(7) both give 7.
It helps when only the size of a difference matters, not its direction: the distance between values, a deviation from a target, comparing with a tolerance.
For complex numbers it returns their magnitude, for example abs(3 + 4j) is 5.0.
Syntax
#Syntax
abs(x)Parameters
#x
a number
An integer, float, or complex number.
Good practices
#- When comparing floating-point numbers, check
abs(a - b) < 1e-9or usemath.isclose(). - The closest result to a target:
min(results, key=lambda r: abs(r - target)).
Related entries
#Spotted a mistake or missing an example? Write to us.