blog banner for post titled: python absolute value

Python has several functions that are pre-defined in Python, known as built-in functions. These functions provide convenience and are very easy to use. In this tutorial, we will be looking at the abs() built-in function to calculate the absolute value of a number. As always, there are other ways to calculate an absolute value in Python, and we can apply the calculation to different data structures. Read on to find out how to do it.

What is an Absolute Value?

The absolute value in mathematics is the distance of a number from zero.

Absolute numbers are always non-negative, and the absolute value of a negative number is equal to the absolute value of its positive equivalent. Because the absolute value captures the distance between two points, it is generalizable and vital in many areas of mathematics, such as calculus and metric spaces.

Visual Representation of Absolute Value

Visual of Python abs() function as distance from zero
Visual representation of Python abs() function as the distance of a number from zero

The diagram shows that negative five is a five-unit measure from zero. Therefore its absolute value is five and not negative five. The number five is five-unit measures from zero, and therefore its absolute value is also five.

Python Absolute Value

The abs() function takes only one argument.

abs(value)

The argument can be an integer or a floating-point number. abs() will return its magnitude if the argument is a complex number.

Get Absolute Value of Integers

calculating absolute value of integer
Calculation of absolute value of integer using abs() function

To get the absolute value of an integer, we use the whole number as the argument for the abs() function. Let’s take a look at several examples.

# Collection of Integers

intA = 4

intB = -334

intC = -5544001

intD = 0

# Absolute values of integers

absA = abs(intA)

absB = abs(intB)

absC = abs(intC)

absD = abs(intD)

#Print out the results

print(f'Absolute values of integers using abs():\n | {intA} | = {absA}')

<meta charset="utf-8">print(f'Absolute values of integers using abs():\n | {intB} | = {absB}')

<meta charset="utf-8">print(f'Absolute values of integers using abs():\n | {intC} | = {absC}')

<meta charset="utf-8">print(f'Absolute values of integers using abs():\n | {intD} | = {absD}')
Absolute values of integers using abs():
 | 4 | = 4

Absolute values of integers using abs():
 | -334 | = 334

Absolute values of integers using abs():
 | -5544001 | = 5544001

Absolute values of integers using abs():
 | 0 | = 0

We can see from the printout that every absolute value is positive or zero.

Get Absolute Value of Floating-point numbers

calculating absolute value of float
Calculation of absolute value of a floating-point number using abs() function

Floating-point numbers are numbers with a decimal point. In other words, they represent fractional values. We can use the absolute function on floating-point numbers. Let’s look at some examples:

# Some floating-point values

floatA = -23.45

floatB = -0.00015

floatC = 875344.12

floatD = 2.098892124

# Get the absolute values of the floating point values

absFloatA = abs(floatA)

absFloatB = abs(floatB)

absFloatC = abs(floatC)

absFloatD = abs(floatD)

# Print out the results

print(f'Absolute values of floating-point values with using abs():\n | {floatA} | = {absFloatA}')

print(f'Absolute values of floating-point values with using abs():\n | {floatB} | = {absFloatB}')

print(f'Absolute values of floating-point values with using abs():\n | {floatC} | = {absFloatC}')

print(f'Absolute values of floating-point values with using abs():\n | floatD} | = {absFloatD}')
| -23.45 | = 23.45

| -0.00015 | = 0.00015

| 875344.12 | = 875344.12

| 2.098892124 | = 2.098892124

The printouts maintain the digits after the decimal point.

Get Absolute Floating-Point Values with Python’s math.fabs() function

We can also import the math library and use math.fabs() to return the absolute value as a floating-point value. The function will always return a floating-point value even if the argument is an integer. Let’s use math.fabs() with a floating-point value and an integer.

import math

# Using math.fabs() on floating point value
print(math.fabs(-5.65))

# Using math.fabs() on integer
print(math.fabs(2))
5.65

2.0

Get Absolute Value of Complex Numbers

calculating absolute value of complex number
Calculation of absolute value of complex number using abs()function

The absolute value of a complex number, a + bi, is the distance between the origin (0, 0) and the point (a, b) in the complex plane, and the formula is

\sqrt{a^{2} + b^{2}}.

Let’s look at an example of calculating the absolute value of a complex number programmatically. In Python, the j replaces i.

# Get Absolute Value of Complex Number

complex_number = 3 - 4j
abs_val = abs(complex_number)
print(abs_val)
5.0

Here we can see we have calculated \sqrt{3^{2} + 4^{2}} to obtain 5 as the absolute value.

Get Absolute Values from Python List of Numbers

You may encounter lists of numbers and need to convert all the numbers to their absolute values.

We can use a for loop or a list comprehension to do this. We will look at how to do both, starting with the for loop.

# Get Absolute Values from Python List of Numbers using a For Loop

a_list = [-32, 560, 20.4, -1.00003]

abs_list = []
for value in a_list:
    abs_val = abs(value)
    abs_list.append(abs_val)

print(abs_list)
[32, 560, 20.4, 1.00003]

In the code, we create a new empty list, loop over the list containing the numbers and calculate the absolute value for each element in the list, then append the values to the new list.

Let’s look at the list comprehension method. In this case, we do not have to create an empty list, resulting in fewer lines of code.

# Get Absolute Values from Python List of Numbers using a For Loop

a_list = [-32, 560, 20.4, -1.00003]

abs_list = [abs(value) for value in a_list]

print(abs_list)
[32, 560, 20.4, 1.00003]

Get Absolute Value from Numpy Array

Numpy arrays are list-like structures that we can use for data manipulation and analysis. These arrays have built-in functions, which are not present for Python lists. We can use np.abs() to calculate the absolute values of all numbers in a NumPy array and return them in a NumPy array.

# Using np.abs to calculate the absolute values of a NumPy array

import numpy as np

an_array = np.array([5, -75, 102, 888, -3.1])

abs_array = np.abs(an_array)

print(abs_array)
[  5.   75.  102.  888.    3.1]

The np.abs() function returns the absolute of integer values as integers and the absolutes of floating-point values as floating points.

Get Absolute Value using Pandas DataFrames

We can use Pandas to analyze and manipulate tabular data using the pandas.DataFrame object. We can use the abs() function on columns of data and assign the values to a new column to display the transformations. Pandas uses the NumPy abs() method shown above for its speed of transformations. Let’s look at an example of converting displacement, which can take positive and negative values to distance, which is an absolute value or scalar.

# Get Absolute Value using Pandas DataFrames

import pandas as pd

df = pd.DataFrame({
'Name': ['Tim', 'Pauline', 'Raoul', 'Dimitris'],
'Displacement': [45, -322, 2.45, -50]
})

df['Distance'] = df['Displacement'].abs()

print(df)
       Name  Displacement  Distance
0       Tim         45.00     45.00
1   Pauline       -322.00    322.00
2     Raoul          2.45      2.45
3  Dimitris        -50.00     50.00

To learn more about using Pandas for data analysis, visit the complete Pandas tutorial for beginners.

Get Absolute Value without Built-in Function

You may have to calculate the absolute value of a given number without using the abs() or math.fabs() functions, for example, in a coding challenge or an interview. To calculate the absolute value of a number, you need to square the number then find its square root. Let’s look at an example.

# Calculating the Absolute function of a number without the abs or fabs() function

int_x = -7.5
abs_x = ((int_x) ** 2) ** 0.5
print(abs_x)

Ensure you wrap the number in its parentheses. If the number is negative and you square it without those extra parentheses, the resultant square will be negative, and the square root will be complex.

We can also use math.sqrt instead of raising to the power of 0.5.

import math

int_x = -7.5

abs_x = math.sqrt((int_x) ** 2)

print(abs_x)
7.5

Summary

Congratulations on finishing the tutorial. You know how to calculate the absolute value of integers, floating-point values, complex numbers, lists, NumPy arrays, and DataFrames. You can use Python’s built-in function abs(), math.fabs(), and numpy.abs(). To summarize, the absolute value of a number is its distance from zero and is always positive even if the candidate number is negative. We can also use the square root of a number squared to calculate the absolute value without built-in functions. The ease of use of built-in functions is one of the reasons Python is among the most popular programming languages for data science and machine learning.

Now you can go and calculate absolute values like a Python pro!

Have fun and happy researching!