What is Python Absolute Value abs() Function?
The abs() function in Python is used for obtaining the absolute value or the positive value of a number.
The syntax is abs(x) where x can be an integer, complex number or a floating number. If the argument x (integral value) is a float or integer, then the resultant absolute value will be an integer or float respectively.
If the argument x (integral value) is a complex number, the return value will only be the magnitude part that can be a float point. For floating number arguments, a floating value is returned.
Syntax of Python abs() function
abs(x)
//where x can be an integer, complex number or a floating number
Parameter of Python abs()
x: integral value for which absolute value will be returned
With the help of a single argument, Python abs() method enables you to find the absolute value of integers, floating numbers as well as the magnitude of complex numbers.
Return Value of Python abs()
Abs() function returns the absolute value of an integer or a floating number in Python. In case the number you enter is a complex number, abs() will return the magnitude of the number.
Therefore, Return Value For:
- Integer = Abs absolute value of Integer
- Floating Number = Abs absolute value of a floating number
- Complex Number = Magnitude of a complex number
An example of a program to return the absolute value of an integer is as follows-
1) #random integer
i = -36
print('The absolute value of -36 is:', abs(i))
Output
The absolute value of -36 is: 36
2) #random floating number
If you wish to find out the absolute value of a floating number, the program remains the same. An example of that is-
fn = -3.144
print('The absolute value of -3.144 is:', abs(fn))
Output
The absolute value of -3.144 is: 3.144
3) #random complex number
If you want to find the magnitude of a complex number, you can follow this example
cn = (3 - 5j)
print('The magnitude of 3 - 5j is:', abs(cn))
Output
The magnitude of 3 - 5j is: 5.830951894845301
Python Abs() Example
print("Absolute Function Program");
#float
float = -119.34
print('Absolute value of integer is:', abs(float))
#integer
int = -199
print('Absolute value of float is:', abs(int))
#complex number
complex = (4 - 4j)
print('Absolute value or Magnitude of complex is:', abs(complex))
Output
Absolute Function Program
Absolute value of integer is: 119.34
Absolute value of float is: 199
Absolute value or Magnitude of complex is: 5.656854249492381