Home
Python
abs: Absolute Value
Updated May 23, 2023
Dot Net Perls
Abs, absolute value. Sometimes a number is negative: like -100. But we want a distance—an absolute value. With abs we compute absolute values.
math
With an if-statement, we can test for negative numbers and make them positive. But imagine doing this many times in a program. Abs is clearer.
Core example. A common math method is abs. This computes absolute values. It removes the negative sign (if there is one) from the number and returns that.
Info The abs method is not part of the math module. Instead, you can use it directly in your programs.
Note The absolute value of zero is zero. This is well-known but good to test in a program.
# Negative number. n = -100.5 # Absolute value. print(abs(n)) # Positive numbers are not changed. print(abs(100.5)) # Zero is left alone. print(abs(0))
100.5 100.5 0
Benchmark, abs. Are math methods fast? Could we rewrite the abs() method with an if-else statement to compute absolute values faster?
if
Version 1 This version of the code uses the abs() method to compute the absolute value of a number.
Version 2 Here we use an inlined if-else statement to compute the absolute value.
Result Using an if-else to compute the absolute value was faster. But the difference here is not relevant to many programs.
import time print(time.time()) # Version 1: compute absolute value with abs. a = -1 i = 0 while i < 10000000: b = abs(a) i += 1 print(time.time()) # Version 2: compute absolute value with if-statement. a = -1 i = 0 while i < 10000000: if a < 0: b = -a else: b = a i += 1 print(time.time())
1346355970.511 1346355973.081 (Abs = 2.57 s) 1346355975.509 (If = 2.428 s)
Hash codes. When computing a hash code (a number based on data and used for lookup) we sometimes end up with a negative value. Abs fixes that.
And We can access elements in a list with positive values returned by abs. This can speed up programs.
With absolute values, we convert negative numbers to positive ones. This helps when computing "distances" from positions. With abs, a built-in, we do this with no extra code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 23, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen