In this article, you’ll learn about absolute values – what they are, how they’re used, and how to use the Python abs() function to calculate them.
What is the Absolute Value of a Number?
A number’s sign is whether it is positive or negative. So, the absolute value of a number is never negative. To make it simple, consider the absolute value of a number that numbers distance from 0.
It is also referred to in mathematics and other programming languages as the modulus or magnitude of a number.
Here are some examples to illustrate:
When writing mathematical equations, it is denoted as |x| (surrounding the number, x, with two vertical bars).
How/Why are Absolute Values Used?
Absolute values are most often used when dealing with distances (mapping) and physics (simulation, games) calculations.
For example, when calculation speed or direction, you measure that speed or direction in relation to a fixed point. The movement to the right may be considered positive, and movement to the left negative.
So, if you’ve moved 20m to the left, your position from the point of origin would be -20, but you can’t have a negative distance (there’s no such thing as a negative kilometer) – so to calculate the distance from the point of origin you’d use the absolute value of your new position:
|-20| = 20
This may seem like a trivial difference – but it becomes crucial when calculating an object’s position and movement – if you want to make video games, you’ll be using it a lot!
The Python abs() Function Syntax
The built-in Python abs() function calculates the absolute value of a given number. Here’s the syntax:
Any kind of number can be passed to abs()
The Python abs() Function Examples
abs(4) # Returns 4 abs(-4) # Returns 4 abs(-2.5) # Returns 2.5