Abs
, absolute valueSometimes 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.
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.
abs
method is not part of the math module. Instead, you can use it directly in your programs.# 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
abs
Are math methods fast? Could we rewrite the abs()
method with an if-else
statement to compute absolute values faster?
abs()
method to compute the absolute value of a number.if-else
statement to compute the absolute value.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)
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.
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.