Home Python How to calculate the Absolute Value in Python

# How to calculate the Absolute Value in Python

There are numerous ways to interact with positive and negative values in Python. But sometimes, all we need to do is double-check that our value isn’t negative. Let’s look at how absolute value can help.

The absolute value of an integer is the distance between it and zero. Because negative five is five units from zero, its absolute value is five, not negative five. This mathematical notation is straightforward, yet it has some more complicated implications. Don’t worry—you don’t need to be an expert on integrals or differentiable functions to understand and use Python’s absolute value function.

## Python Absolute Value

In Python, absolute values are useful in returning a number’s absolute value. When a negative value is supplied as an argument (for example, -98), Python returns the appropriate positive number (e.g., 98).

To establish an understanding of its working, we must first comprehend what absolute value is. The number line’s distance between any number and 0 is known as the absolute value. These numbers are frequently used in mathematics, data science, and physics domains. On the other hand, developers typically utilize it to remove unfavorable indications. Python delivers the same value whether a positive number or 0 is supplied as an argument. The number line’s distance from 0 is exactly that.

In Python, there are two techniques to acquire absolute values.

In mathematics, the absolute value of an integer is its non-negative value regardless of its sign. Put another way. The absolute value is a number’s distance from zero.

```The absolute value of -36, for example, is 36.
The absolute value of 18 is just that: 18.```

Our application employs absolute values when we don’t care about the sign and only want the value. The absolute value of a number is obtained in Python in two ways:

• The abs() method in Python returns the absolute value.
• The math.fabs() method returns the absolute value and a floating-point value.

Ninety-five percent of the time, the ordinary abs() function will suffice. So let’s get started with it.

### The abs() method in Python returns absolute values.

abs() refers to a function that is built-in and is tasked with returning the absolute value. The function only requires one argument, which must be a number. The absolute value of that argument is then returned. To utilize the method, call abs() whenever an absolute value is required:

`abs(-83.63)`

The abs() method returns a variety of values:

• abs() returns the absolute integer or float value when given an integer or float value.
• However, if we pass a complex number to abs(), the function returns the magnitude of that number.
• abs() can handle binary, octal, and even infinite integers.

### In Python, find the absolute value of an integer

To find the absolute value of an integer, we use the abs() function with the full number. Consider the following scenario:

```# Integers at random

first_variable = 43
second_variable = -123
third_variable = 0
fourth_variable = -9116439

# Calculate the absolute values of the numbers.
abs_first = abs(first_variable)
abs_second = abs(second_variable)
abs_third = abs(third_variable)
abs_fourth = abs(fourth_variable)

#Produce the results
print(" Integer absolute values with `abs()`:")
print("|", first_variable, "| = ", abs_first, sep="")
print("|", second_variable, "| = ", abs_second, sep="")
print("|", third_variable, "| = ", abs_third, sep="")
print("|", fourth_variable, "| = ", abs_fourth, sep="")```

This program creates four integer variables first (first_variable through fourth_variable). A positive value, two negatives, and zero are all present. We now need to calculate their absolute value.

The abs() function is then applied to each variable. It gives us a value that indicates how distant a number is from zero. These values are now stored in four new variables, abs_first through abs_fourth. With Python’s print() method, we output both the original number and its absolute value. It is how the output appears:

### How to get the absolute value of floating-point values in Python

Of course, we can also calculate the absolute value of fractional quantities. We simply call abs() on that value to accomplish this. Here’s an illustration:

```# Some random floating-point values
first_variable = -12.34
second_variable = -1.8457425364
third_variable = -0.00000000001
fourth_variable = 9424.5895279095

# Get the absolute value of each variable
first_abs_var = abs(first_variable)
second_abs_var = abs(second_variable)
third_abs_var = abs(third_variable)
fourth_abs_var = abs(fourth_variable)

# Output the results
print(" Absolute values of floating point numbers `abs()`:")
print("|", first_variable, "| = ", first_abs_var , sep="")
print("|", second_variable, "| = ", second_abs_var, sep="")
print("|", third_variable, "| = ", third_abs_var , sep="")
print("|", fourth_variable, "| = ", fourth_abs_var, sep="")
```

This mini-program creates four floating-point variables. first_variable through fourth_variable are their names. After that, we obtain their absolute values. We use the abs() function on each variable to accomplish this. The function’s result is saved in a new variable (first_abs_var till fourth_abs_var). The findings are then displayed using many print() instructions. The original variable and its absolute value are output by each:

Of course, we can also calculate the absolute value of fractional quantities. We simply call abs() on that value to accomplish this. Here’s an illustration:

```# Some random floating-point values
first_variable = -12.34
second_variable = -1.8457425364
third_variable = -0.00000000001
fourth_variable = 9424.5895279095

# Get the absolute value of each variable
first_abs_var = abs(first_variable)
second_abs_var = abs(second_variable)
third_abs_var = abs(third_variable)
fourth_abs_var = abs(fourth_variable)

# Output the results
print(" Absolute values of floating point numbers `abs()`:")
print("|", first_variable, "| = ", first_abs_var , sep="")
print("|", second_variable, "| = ", second_abs_var, sep="")
print("|", third_variable, "| = ", third_abs_var , sep="")
print("|", fourth_variable, "| = ", fourth_abs_var, sep="")```

This mini-program creates four floating-point variables. first_variable through fourth_variable are their names. After that, we obtain their absolute values. We use the abs() function on each variable to accomplish this. The function’s result is saved in a new variable (first_abs_var till fourth_abs_var).

The findings are then displayed using many print() instructions. The original variable and its absolute value are output by each:

### Using the math.fabs() function to generate absolute float values in Python

Python has the math.fabs() function in addition to the conventional abs() method. One argument is also required for this function. The absolute value of that argument is then returned as a floating-point value. That behavior is similar to abs(), but one major difference is that we always get a floating-point value back – even when we pass math. To begin, give fabs() an integer. To use math.fabs(), just type:

```import math

math.fabs(-38)
# Returns: 38.0```

### Example: Get absolute values as floating-point numbers

So we call math.fabs() on a numerical value to get the absolute value as a floating-point value. Consider the following scenario:

```import math

# sample random values
first_value = -4
second_value = -56
third_value = 26
fourth_value = -2.992474203

# Get the floating-point absolute value from each
first_fabs = math.fabs(first_value)
second_fabs = math.fabs(second_value)
third_fabs = math.fabs(third_value)
fourth_fabs = math.fabs(fourth_value)

# displaying the resultant results
print("Showing the resultant absolute floating-point values `fabs()`:")
print("|", first_value, "| = ", first_fabs, sep="")
print("|", second_value, "| = ", second_fabs, sep="")
print("|", third_value, "| = ", third_fabs, sep="")
print("|", fourth_value, "| = ", fourth_fabs, sep="")```

We use math to determine their absolute value. On each variable, use the fabs() method. It gives us the absolute value in decimal form. The first_fabs through fourth_fabs variables are used to hold the results. The print() method is used in the final section to display the original and absolute value. Each value returns as a floating-point value, as shown in the output:

### Use a Python list or array to get absolute values.

Abs returned the absolute value of a single value () and math.fabs() in the instances above. But what if we have a set of values to work with? Let us investigate.

First, get the absolute value of a Python list’s numbers. The absolute value of each list value is obtained in numerous methods in Python. A list comprehension expression is one choice. It is a neat and efficient approach to converting a whole list into absolute values. Consider the following scenario:

```# a few arbitrary figures
integer_values = [-40, 58, -69, -84, 51, 76, -12, 36]

# For each number, find the absolute value.
absolute_values = [abs(num_var) for num_var in integer_values ]

# Output data
print("The original numbers include:\n", integer_values)
print("The absolute values include:\n", absolute_values)```

We start by making a list of named values in this sample program above. It has positive and negative integer values. After that, we create a list of comprehension.

The function ‘abs()’ returns the absolute value of each numeric value between square brackets ([and]). Our values list contains the number variable. We make it with a for expression: for number in values in-line. It creates a new list with each original list value’s absolute value. The print() function then prints both the original and the absolute value list. The following is how the output appears:

If you don’t need to maintain the original list values, set the original list to the list comprehension result. For example:

```# Some example values
integer_values = [-40, 58, -69, -84, 51, 76, -12, 36]

# Substitute the absolute values for the original numbers.
integer_values = [abs(num_var) for num_var in integer_values]```

### Using a Python loop to get absolute values from a list

While list comprehensions are useful, they aren’t appropriate in all situations. The standard for loop is generally a superior alternative, especially if we want to process values in addition to just getting the absolute value. When finding the absolute value of negative values in our list, we want to multiply positive values by 2. With a Python loop, we can accomplish this:

```# sample positive and negative numbers
integer_values = [-40, 58, -69, -84, 51, 76, -12, 36]

# Negative values have an absolute value, but
# multiply positive numbers by two

vals_processed = []
for val in integer_values:
if val < 0:
vals_processed.append(abs(val))
else:
vals_processed.append(val * 2)

# Output data
print("These are the original numbers:\n", integer_values)
print("These are the resulting processed numbers:\n", vals_processed)```

We start by making a numerical list. There are both positive and negative integers in that values list. Then we create a new, processed list. This list starts empty (but gets filled inside the loop). Then we build a for a loop. This loop iterates across the list of values. During each loop cycle, the number variable represents a list value.

An if/else statement inside the loop examines that variable. The abs() function takes its absolute value when less than zero. The value is then appended to our processed list using the list’s append() method. The else clause is executed when the loop variable is zero or more. The variable is then multiplied by two and added to the list. Python’s print() method outputs the original and processed list in the final line of code. This is what it produces:

If you don’t require the original list values, you can use the for loop to rewrite the list. Python’s enumerate() a method is a helpful tool. This is how it appears:

```# sample integer values as either positive and negative
integer_values = [-40, 58, -69, -84, 51, 76, -12, 36]

#Replace each integer with its absolute value as you loop through the list.
for i, num in enumerate(integer_values):
values[i] = abs(num)```

### Use a Python array to get absolute values

Getting the absolute values of positive and negative values in a Python array is comparable to working with lists. Consider the following scenario:

```import array

# Creation of an array  containing random values
integer_values = array.array('i', [-40, 58, -69, -84, 51, 76, -12, 36])

# Make a new array with the absolute values
abs_vals = array.array('i', [abs(num) for num in integer_values])

# Output the results
print("The initial array of values is:\n", integer_values)
print("The resultant absolute values is:\n", abs_vals)```

We begin by importing the array module. The array.array() constructor is then used to create an array. There are both positive and negative integers in that array.

Then, using the absolute values of the first array, we create a second array. To accomplish this, we use list comprehension to build the array. That expression calculates the absolute value (abs(value)) of each number generated by the in-line for expression (for value in values). We then go through the original list and collect the absolute values.

The print() function outputs the original and absolute value array in the final line of code. This is how it appears:

If you don’t require the original data, you can just overwrite the array with absolute values. For instance:

```integer_values = array.array('i', [-40, 58, -69, -84, 51, 76, -12, 36])

# Overwriting the already present array with the new absolute values
integer_values = array.array('i', [abs(num) for num in integer_values])```

### Use a NumPy array to get absolute values

You might have a NumPy array from which you desire the absolute values if you work with the NumPy Python numeric programming module. This is how we go about it:

```import numpy

integer_values = numpy.array([-40, 58, -69, -84, 51, 76, -12, 36])

# Create an absolute value array from scratch.
abs_vals = numpy.abs(integer_values)

print("These are the initial  NumPy array values:\n", integer_values)
print("These are the resultant absolute values:\n", abs_vals)```

The NumPy module is initially imported into this code. Then we create an integer_values array that contains both positive and negative numbers. We use numpy to get their absolute values.

Use the abs() function with that array as an input. NumPy then returns a new array containing the absolute values of each number in the original array. That array is called abs_vals. Both arrays are displayed in the final print() instructions. Numpy.abs() returned the absolute value for each of the original array values, as shown in the output:

If the original data isn’t required, you can overwrite the existing array with the absolute values.

This is how:

```integer_values = numpy.array([-40, 58, -69, -84, 51, 76, -12, 36])