All sorts of mathematical calculations often require computation with absolute values of numbers. The absolute value in Python is calculated in several ways.
Absolute value is the non-negative value of a given number.
Here we will cover the four most used methods with time analysis and estimate which of the ways is the fastest and best use cases for each.
Time analysis is measured using decorator @time_decorator. All values are displayed in nanoseconds (ns).
In the following list, you can see the syntax of all the methods.
abs(x)
math.fabs(x)
numpy.abs(x)
( x**2 ) ** 0.5
-x if x < 0 else x
Parameters
- x – numeric expression
Python absolute value with abs
Using abs is the most obvious way to calculate the absolute value.
Abs is a built-in function, there is no need to import. The Python interpreter recognizes the syntax of built-in functions, and they are always available.
WARNING - Python’s abs function does not belong to the math module.
abs(-5) abs(-5.0) abs(-5j) # Output: # 5 # 5.0 # 5.0
Integer | Float | Complex | |
Return value | int | float | float |
If given a complex number, abs returns its magnitude.
NOTE - magnitude is sqrt(a2 + b2)
Abs supports integer, float, and complex numbers and all objects with the __abs__ method implemented.
Let’s check the time analysis below.
Time analysis of abs function
I will display the absolute value in Python time analysis in nanoseconds (ns).
Example 1.
@time_decorator def abs_function(x): return abs(x) abs_function(-5) # Output: # Total execution time: 188 ns
The average execution time based on 100 executions is 189 ns.
Python absolute value with math.fabs
In addition to the built-in functions, we also have a math module that provides mathematical functions.
By default, all return values are float. Math.fabs function is no different.
Complex numbers are not supported.
Example 1.
math.fabs(5) math.fabs(-5) math.fabs(-5j) # Output: # 5.0 # 5.0 # TypeError: can't convert complex to float
Integer | Float | Complex | |
Return value | float | float | TypeError |
Time analysis of fabs function
@time_decorator def fabs_function(x): return math.fabs(x) fabs_function(-5) # Output: # Total execution time: 241 ns
The average execution time based on 100 executions is 247ns.
Python absolute value with numpy.abs
NumPy, one of the most popular libraries in Python that handles matrices and lists, also has excellent support for mathematical operations.
We will cover the numpy.abs method.
Example 1.
numpy.abs(-5) numpy.abs(-5.0) numpy.abs(-5j) # Output: # 5 # 5.0 # 5.0
Integer | Float | Complex | |
Return value | numpy.int64 | numpy.float64 | numpy.float64 |
NOTE - numpy.abs support lists and return numpy.ndarray with positive numbers! - numpy.abs and numpy.absolute are completely identical.
Time analysis of numpy.abs function
@time_decorator def numpy_function(x): return numpy.abs(x) numpy_function(-5) # Output: # Total execution time: 929 ns
The average execution time based on 100 executions is 952ns.
Python absolute value implementation
There are two ways to implement your absolute value. Here we will show both.
The first consists of squaring the number (we get a positive squared number) and then rooting, in which we get a non-square positive value of the initial number.
The second is probably more apparent. If the number is negative, we multiply it with -1, leaving us with a positive number.
Example 1.
# squaring and then rooting ( x**2 ) ** 0.5
Integer | Float | Complex | |
Return value | float | float | complex |
# if negative, multiply with -1 -x if x < 0 else x
Integer | Float | Complex | |
Return value | int | float | TypeError: ‘<‘ not supported between instances of ‘complex’ and ‘int’ |
Time analysis of implementation
@time_decorator def square_root(x): return (x ** 2) ** 0.5 square_root(-5) # Output: # Total execution time: 449 ns
The average execution time based on 100 executions is 451ns.
@time_decorator def minus_negative(x): return -x if x < 0 else x minus_negative(-5) # Output: # Total execution time: 187 ns
The average execution time based on 100 executions is 185ns.
Conclusion
I hope you now have a better understanding of calculating absolute value in Python. Each of these methods has some advantages and disadvantages that you must recognize concerning the use case. Whether you need performance, computing with lists, or working with complex numbers.
Considering the performance, these are the results:
abs | math.fabs | numpy.abs | sqrt(x2) | -x if x < 0 | |
Speed (based on 100 iterations) in ns | 189 | 247 | 952 | 451 | 185 |
NOTE - Tested in Python 3.10 version. In other versions, the results could be slightly different. - The results will and should vary depending on the specifications of the computer you are using.
That’s all and stay positive. 🙂
System specs: CPU: Intel® Core™ i5-7200U CPU @ 2.50GHz × 4 GPU: NV117 / Mesa Intel® HD Graphics 620 RAM: 8GB Python 3.10.1 [GCC 9.3.0] on Linux