The abs() function in Python returns the absolute value of a given number.
The number could be a negative or positive integer, decimal (floating point) number or “complex” number. If the number is complex, abs() returns the magnitude of the complex number.
Let’s see what that means:
Take this example showing the three scenarios:
print("Absolute value of -5 is: ", abs(-5)) print('Absolute value of -8.67 is:', abs(-8.67)) print("Absolute value of 5+3j is: ", abs(3+2j))
Absolute value of -5 is: 5 Absolute value of -8.67 is: 8.67 Absolute value of 3+2j is: 3.605551275463989
In the above example
- Line one is printing the absolute value of -5 which is 5
- Line two is printing the absolute value of -8.67 which is 8.67
- Line three is printing the magnitude of the complex number 3+2j which is 3.605551275463989 (it’s the square root of 3*3 plus 2*2 in this case).
What is a complex number you might ask?
A complex number is a an extension of the real number system in which all numbers are expressed as a sum of a real part and an imaginary part.
Another way of saying it: a complex number is a number that can be expressed in the form a + bi, where a and b are real numbers, and i is a symbol called the imaginary unit satisfying the equation i*i = −1.
So, in the example of 3+2j, the real part is the 3 and the imaginary part is 2j.
By the way, imaginary numbers allow people to find the square root of negative numbers, like get the square root of -25. The applications of imaginary (and complex) numbers include electrical engineering and even quantum mechanics. But that goes beyond the point of this article 😉
And what does magnitude mean?
The magnitude (or absolute value) of a complex number is the number’s distance (or length) from the origin in the complex plane. And you can find the magnitude using the Pythagorean theorem.
Like this, where the magnitude is the square root of 3*3 plus 2*2 = ~3.605
And there you have it, the Python abs() function demystified 🙂
Mike is the creator of Go With Code and a coder at heart 🙂