Home » Programming » Python » Python Absolute Value

Calculating Absolute Values in Python, With Examples

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?

The absolute value of a number is that number’s value without any regard to its sign.

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:

Number Absolute/Modulus Value
4 4
-4 4
-2.5 2.5
x x

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:

abs(NUMBER)

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

Easy!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment