C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Built-in: The abs method is not part of the math module. Instead, you can use it directly in your programs.
Zero: The absolute value of zero is zero. This is well-known but good to test in a program.
Python program that uses abs
# 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))
Output
100.5
100.5
0
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.
Python program that benchmarks abs
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())
Output
1346355970.511
1346355973.081 (Abs = 2.57 s)
1346355975.509 (If = 2.428 s)
And: We can access elements in a list with positive values returned by abs. This can speed up programs.