Function signature
abs(num)
Parameters
num - An integer, a floating-point number or a complex number.
Return value
The absolute value of the given number.
Overview
- The Python built-in function abs() returns the absolute value of a given number.
- For any integer i, real number r, the absolute value is the magnitude of the number without the associated sign part.
- For any complex number z = x + jy, the absoulte value is given by the square root of x**2 + y**2.
- x - The real part of the complex number.
- y - The imaginary part of the complex number.
Example 1 - Absolute value of integers and real numbers
# Example Python program that finds the absolute
# value for a given integer and a floating-point
# number using the built-in function abs()
# Absolute value of a negative integer
negativeInt = -7
absValue = abs(-negativeInt)
print("Absolute value of negtive integer {}:{}".format(negativeInt, absValue))
# Absolute value of a negative floating point number
negativeReal = -7.5
absValue = abs(-negativeReal)
print("Absolute value of negative real number {}:{}".format(negativeReal, absValue))Output
Absolute value of negtive integer -7:7
Absolute value of negative real number -7.5:7.5Example 2 - Absolute value of complex numbers
# Example Python program that finds the absolute value of
# complex numbers using the built-in function abs()
# Create a complex number
realPart = -7.0
imgPart = 2.0
complexNum = complex(realPart, imgPart)
absValue = abs(-complexNum)
print("Absolute value of the complex number {}:{}".format(complexNum, absValue))
# Create another complex number whose imaginary part is zero
realPart = 2.0
imgPart = 0.0
complexNum = complex(realPart, imgPart)
absValue = abs(-complexNum)
print("Absolute value of the complex number {}:{}".format(complexNum, absValue))Output
Absolute value of the complex number (-7+2j):7.280109889280518
Absolute value of the complex number (2+0j):2.0