Absolute Value Python function with Examples

Posted by Marta on December 18, 2020 Viewed 67 times

In this article I will explain how to calculate the absolute value in python, provide you with some examples and some coding problems

Card image cap

In this article I will explain how to calculate the absolute value in python, provide you with some examples and some coding problems where you will need to use the absolute value python function.

The abs() function is a built-in function that returns the absolute value for a given number, this basically means removing the negative sign.

In math, the absolute number is described as the distance of a number from zero.

To provide you with some examples, the absolute number of -10 is 10. The absolute value of 80 is 80.

Syntax

abs(value)

Where value is the number to which you would like to apply the absolute value operation. 

This number could be an integer, float a complex number.

In case the value argument is an integer or a float, the abs function will return a number of the same type.

If the argument is a complex number, the function returns the magnitude of the complex number. The magnitude is the number’s distance from the origin in a complex plane.

Examples

Example with an integer

integer_var1 = 10
absolute_value1 = abs(integer_var1)
print("Absolute of "+str(integer_var1)+" = "+str(absolute_value1))

integer_var2 = -10
absolute_value2 = abs(integer_var2)
print("Absolute of "+str(integer_var2)+" = "+str(absolute_value2))

Ouput:

Absolute of 10 = 10
Absolute of -10 = 10

Example with a float

float_var1 = 10.5
absolute_value1 = abs(float_var1)
print("Absolute of "+str(float_var1)+" = "+ str(absolute_value1))

float_var2 = -10.5
absolute_value2 = abs(float_var2)
print("Absolute of "+str(float_var2)+" = " + str(absolute_value2))

Output:

Absolute of 10.5 = 10.5
Absolute of -10.5 = 10.5

Example with a complex number

complex_num1 = 3 + 2j
absolute_value1 = abs(complex_num1)
print("Absolute( or Magnitude) of "+str(complex_num1)+" = " + str(absolute_value1))

complex_num2 = -3 + 2j
absolute_value2 = abs(complex_num2)
print("Absolute( or Magnitude) of "+str(complex_num2)+" = " + str(absolute_value2))

Output:

Absolute of (3+2j) = 3.605551275463989
Absolute of (-3+2j) = 3.605551275463989

What if I pass a something invalid, like a String?

In case you pass an argument that is not valid. Anything that is not integer, float or a complex number, the function returns a bad operand type error, like the one below

string1 = '3'
absolute_value1 = abs(string1)
print(absolute_value1)

Output:

Traceback (most recent call last):
  File "/Users/martarey/dev_python/python_projects/absolute.py", line 3, in <module>
    absolute_value1 = abs(string1)
TypeError: bad operand type for abs(): 'str'

Some use cases

So far we have seen how to use the absolute function, the arguments, valid input, however how is this useful in real life? Excellent question. Here are some coding exercises where you will need to the absolute value function.

Case1: Multiply without multiplication operator

Let’s see one example where you could the absolute value function. Let’s say you need to multiply two numbers. However you can’t use the multiplication or division operator. To solve this problem you will need to use the absolute value. Here is one possible way to solve this problem:

def multiply(multiplicand, factor):
    result=0
    for index in range(1,abs(factor)+1):
        result = result + multiplicand

    if factor<0:
        return -result
    else:
        return result

print(" 20 x 5 = "+str(multiply(20,5)))
print(" -20 x 5 = "+str(multiply(-20,5)))
print(" 20 x -5 = "+str(multiply(20,-5)))
print(" -20 x -5 = "+str(multiply(-20,-5)))
print(" 20 x 0 = "+str(multiply(20,0)))

Output:

  20 x 5 = 100
  -20 x 5 = -100
  20 x -5 = -100
  -20 x -5 = 100
  20 x 0 = 0

To get the result of the multiplication, we basically need to add the multiplicand as many times as the factor indicates. Therefore we can ignore the sign of the factor number.

Since we have to add up the multiplicand a fixed number of times, dictated by the factor, a for loop will be a good fit.

And lastly, before returning the result value, we will to add back the sign of the factor that we ignored at the beginning.

Case2: Check variations

In real life another common use of the absolute value is calculating how much a value deviates from an average value, which can be useful for anomaly detection. Let’s see an example where you could apply this.

For instance, let’s say that you work for an smartphone factory and your role is testing brand new smartphones. You need to find faulty smartphone and return them to be repaired. Your company consider an smartphone faulty when its temperature varies 10 degree above or under the average temperate over 10 hours.

Given the average temperature for the smartphone and the temperature for the last ten hours, we could write a function to indicate if an smartphone is faulty or not. Here is a possible way to achieve this:

def is_smartphone_faulty(average_temp, temp_last_ten_hours):
    for temp in temp_last_ten_hours:
        absolute_difference = abs(average_temp - temp)
        if absolute_difference > 10 :
            return True

    return False

smartphone1_faulty = is_smartphone_faulty(15.5, [12.5, 16, 20.5, 13.5, 12.5, 5.5, 3.4, 13.5, 13.9, 14.6])
print(smartphone1_faulty)

smartphone2_faulty = is_smartphone_faulty(15.5, [12.5, 16, 25.5, 13.5, 12.5, 15.5, 13.4, 13.5, 13.9, 14.6])
print(smartphone2_faulty)

Output:

True
False

In this case the absolute value function is used in line 3 of the above code snippet. The absolute value is used to calculate the different between the average temperature value received and the different temperature measurements.

Summary

To summarise, the absolute value function will remove the sign of the value you pass in. It can used with integer, float and complex numbers. Plus we have seen some examples and some use cases where the absolute function is useful.

What’s next?

Four Python project ideas for beginners

Fun things to do with python – Automate Youtube Downloads

Coding Interview Question – Find delivery route

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java