abs: Absolute Value
This page was last reviewed on 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.
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?
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 23, 2023 (edit).
© 2007-2024 Sam Allen.