How to get absolute value in Python without using abs

In this Python tutorial, we will learn how to compute the absolute value without using the built-in function abs() function. In addition, we will explore different ways to achieve that.

Absolute Value in Python

Absolute value is a fundamental mathematical concept, essentially asking the question: “How far is this number from zero?” More technically, the absolute value of a real number x is the non-negative value of x without regard to its sign. In mathematical notation, it’s represented as |x|.

Absolute Value in Python without using abs() function

Python has a built-in function called abs() which provides the absolute value of a number. For instance, abs(-5) will return 5.

But what if we want to compute the absolute value without using this built-in function? So, let’s explore different ways to achieve that.

Using Python Conditional Statements

The simplest way to calculate the absolute value without using the abs() function is through Python conditional statements. You can check if the number is negative, and if so, multiply it by -1 to convert it to positive.

Here’s a simple implementation:

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    if num >= 0:
        return num
    else:
        return -num

# Test the function with positive, negative, and zero values
print(absolute_value(10))  
print(absolute_value(-20))  
print(absolute_value(0))  
  • Here, the absolute_value() Python function takes a numerical input num. It then checks whether num is greater than or equal to zero.
  • If it is, the Python function returns num unchanged, because it’s already a positive number.
  • If num is less than zero (i.e., it’s negative), the Python function returns -num, effectively changing its sign to make it positive.

Output:

How to get absolute value in Python without using abs
Get absolute value in Python without using abs

Using the Python Square Root

Another method involves using the property of Python square roots. The square of any real number, whether positive or negative, is always non-negative. By taking the square root of the square of a number, we can get its absolute value.

Here’s how it can be implemented:

import math

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    return math.sqrt(num ** 2)

# Test the function with positive, negative, and zero values
print(absolute_value(10)) 
print(absolute_value(-20)) 
print(absolute_value(0)) 
  • This Python absolute_value() function takes a number num and first squares it (num ** 2). This will always be a non-negative number.
  • Then, the Python math.sqrt() function takes the square root of this result. The final output is the absolute value of num.

Output:

How to get absolute value in Python without using abs example
Get absolute value in Python without using abs example

Using Python Bit Manipulation

This Python method is a bit complex and is primarily applicable for integers. It involves right-shifting the integer’s bits, which effectively divides the number by 2, and then negating the shifted value if necessary.

Here’s how you can do it:

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

    mask = num >> 31
    return (num ^ mask) - mask

# Test the function with positive, negative, and zero values
print(absolute_value(10))
print(absolute_value(-20))  
print(absolute_value(0))
  • In this code, mask = num >> 31: This right shift operation moves the sign bit (the leftmost bit in a 32-bit integer) to the rightmost position. If num is positive or zero, mask will be 0. If num is negative, mask will be -1 due to the way Python handles right shifts for negative numbers.
  • (num ^ mask) - mask: This expression effectively removes the sign bit from num. The XOR operation (^) flips the bits of num if mask is -1 (i.e., if num is negative) and leaves num unchanged if mask is 0 (i.e., if num is non-negative). Subtracting mask then adjusts the result to be the correct absolute value.

Output:

Get absolute value in Python without using abs
Get absolute value in Python without using abs

Conclusion

While Python’s built-in abs() function is convenient and efficient, there are several alternative methods to calculate the absolute value of a number without using abs().

These methods involve different approaches, from conditional statements to mathematical properties to bitwise manipulation, and serve as a great way to explore Python’s versatility and power.

You may also like to read the following Python tutorials.