Python abs: Absolute Value

This Python example uses the abs built-in to compute absolute values. It uses abs on negative and floating-point numbers.
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.

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
Abs performance. Are math methods fast? In this program, I tested the abs method versus a simple if-else statement that also computes absolute values.If

Info: They compute absolute values of the number a. In the results, doing an if-else statement to compute the absolute value was faster.

But: The difference here is not relevant to many programs. I recommend using abs() for clearer programs.

Python program that benchmarks abs import time print(time.time()) # Compute absolute value with abs. a = -1 i = 0 while i < 10000000: b = abs(a) i += 1 print(time.time()) # 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)
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls