As Python is increasingly used for computation, it becomes more important for math related resources to be made available. To aid in that effort, I figured I’d share a few ways to compute absolute value in Python.
As it turns out, there are a few ways to compute absolute value in Python. First, there’s the
abs() function which comes built in. Alternatively, there’s an arithmetic expression that gets the job done:
(x**2)**0.5. Finally, a quick negative test (i.e.
if x < 0: x = -x works as well. Which one you choose depends on your needs. Luckily, we’ll dig into the details below.
Table of Contents
In mathematics, the absolute value of a number is its magnitude (i.e. ignore the sign). For example, the absolute value of 7 is 7. Meanwhile, the absolute value of -9 is 9.
Naturally, absolute value is used in a lot of different places in mathematics. For example, if we travel to and from the grocery store, our displacement is zero. After all, our starting point and ending point is the same. Or to look at it another way, the two legs of the trip were the same distance with opposite signs:
leg1 = 15 # miles leg2 = -15 # miles displacement = leg1 + leg2
To compute the total distance traveled, we’d compute the absolute value of each leg before summing them:
distance = |leg1| + |leg2|
Of course, if it were that easy to represent operations like absolute value in Python, you probably wouldn’t be here. In other words, we have to go about doing this some other way. Luckily, we’ll cover a few solutions below.
When I set out to write this article, I only knew of two ways to compute absolute value in Python. As it turns out, there are at least three ways to do it:
Below, we’ll break down each solution with an example. Then, in the next section, we’ll check each solution for performance.
Compute Absolute Value by Hand
If the problem with computing an absolute value is the sign, then there’s a pretty straightforward solution:
x = -5 if x < 0: x = -x
Here, we check to see if our value is negative. If it is, we negate it. That way, positive values stay positive, and negative values are made positive.
One way I’ve gotten value out of this solution is in a program where numbers drive the logic. For example, let’s say we have a program which performs an action based on a number input by the user. In this program, the number drives how many times the action occurs while the sign drives which action occurs.
In this program, it’s helpful to assume that the user will enter a positive number. That way, we can use the positive number to drive a loop. If the user doesn’t enter a positive number, we can use this branch to update our expected action as well as compute absolute value.
That said, I generally think the other solutions in this article are more useful.
Compute Absolute Value Using Math
When I was putting together this article, I knew there were essentially two ways to compute absolute value: use a branch or use a function. At the time, however, I wasn’t aware of the following math trick:
x = -5 x = (x**2)**.5
If you’ve ever done any statistics or machine learning, you might know that we often square values, so we don’t have to deal with negative numbers (e.g. mean squared error). That’s exactly why we square our value here. For example, -2 and 2 are both 4 when squared.
Once we have our squared values, we can generate the absolute value by taking the square root. In most languages, computing square root is a bit complicated—would would probably justify another article. Luckily, Python includes power as one of the standard operations. As a result, we can compute square root by raising our base to
In the end, we’ll end up with the expected absolute value with a few caveats:
First, this solution produces a floating point value. In this case,
x will move from
5.0. As a result, if we plan to use
x as a loop counter, we’ll probably want to cast it to an integer.
Second, rounding errors for floating point values may become an issue. I wasn’t able to generate any, but I suspect it’s possible to get an unexpected absolute value with this method.
If you don’t want to deal with these issues, there’s always another solution.
Compute Absolute Value Using Standard Library
Conveniently, Python has bottled up the concept of absolute value for use in the standard library. In fact, there’s no need to import any modules. The following function works right out of the box:
x = -5 x = abs(x)
In other words, if you need to compute an absolute value directly—for instance, as a part of an expression—this is the way to go.
At this point, I figure it’s worth looking at each of these solutions from a performance perspective. To do that, we’ll need to construct a few equivalent code snippets:
setup = """ x = -5 """ control_flow = """ if x < 0: -x """ mathematics = """ (x**2)**0.5 """ function = """ abs(x) """
As you can see, I simplified these expressions a bit because I just wanted to observe the effects of the absolute value computation. In other words, none of these expressions actually change
x. Let’s see how they play out:
>>> import timeit >>> min(timeit.repeat(setup=setup, stmt=control_flow)) 0.04148059999988618 >>> min(timeit.repeat(setup=setup, stmt=mathematics)) 0.3548131000002286 >>> min(timeit.repeat(setup=setup, stmt=function)) 0.05475890000025174
As it turns out, the branch is actually the fastest option. I suspect that the
abs() function is slightly slower due to the function call. At any rate, I was curious to see how these solutions scale, so I decided to change
x to a much larger number:
>>> setup = """ x = -51310834193491 """ >>> min(timeit.repeat(setup=setup, stmt=control_flow)) 0.06167479999976422 >>> min(timeit.repeat(setup=setup, stmt=mathematics)) 0.5422766000001502 >>> min(timeit.repeat(setup=setup, stmt=function)) 0.07209680000005392
Again, the results shook out about the same. Our simple control flow solution is rather quick.
Finally, I decided to look at a positive number:
>>> setup = """ x = 51310834193491 """ >>> min(timeit.repeat(setup=setup, stmt=control_flow)) 0.0271256999999423 >>> min(timeit.repeat(setup=setup, stmt=mathematics)) 0.5370481999998447 >>> min(timeit.repeat(setup=setup, stmt=function)) 0.05108329999984562
Since there’s no branching, we get a bit of a performance boost with our control flow and
abs() solutions. Unfortunately, the mathematics solution is slow no matter how you run it. No wonder I’ve never seen it in practice.
As always, take these test cases with a grain of salt. I ran them using Python 3.7.3 on a Windows machine; your mileage may vary. If you’re interested in learning more about this performance testing process, I have an article for that.
As promised, I’ve brought along a challenge which leverages absolute value. In particular, this challenge is related to the example provided in the control flow solution:
Let’s say we have a program which performs an action based on a number input by the user. In this program, the number drives how many times the action occurs while the sign drives which action occurs.
More specifically, write a program which generates
|x| plus signs if the number is positive and
|x| negative signs otherwise. Here,
x is the number input by the user. As a result, the program should behave as follows:
>>> "Enter a number": 7 +++++++ >>> "Enter a number": -5 -----
As I mentioned, I would likely solve this problem using our control flow sample. Of course, you’re welcome to use any solution available to you. Just remember to drop it in the comments! I’ll be sharing mine there as well.
A Little Recap
With all that out of the way, let’s take a look at our ways to compute absolute value once again:
x = -37 # Compute absolute value by brute force if x < 0: x = -x # Compute absolute value by arithmetic x = (x**2)**0.5 # Compute absolute value with standard library x = abs(x)
As always, if you liked this article, feel free to show it some love by dropping a comment, giving it a share, or any number of other ways. If this article interested you, the following articles are heavily related:
- How to Performance Test Python Code: timeit, cProfile, and More
- How to Sum Elements of Two Lists in Python: Comprehensions and More
In addition, here are a few Python related resources on Amazon (ad):
- Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More!
- Scientific Computation: Python 3 Hacking for Math Junkie
Otherwise, thanks for stopping by! I appreciate your time.
As much as I love to write, I don't read nearly as much as I should. That's why when I recommend an article, you should probably check it out.
If you're looking to learn some Python, I have plenty of practice problems to get you started.