Python abs() method example

Python abs() method returns the absolute value of the given number as method argument. If the given number is a complex number, method abs() returns its magnitude.

  • If the number is an integer with base other than 10 (for example binary, octal, hexadecimal or exponential form), the abs() function will return its value as a decimal integer in base 10.
  • The precise term for absolute value is “non-negative”. The absolute value of any non-zero number can be thought of as it’s the distance from zero and it will always be positive.

    For example, the absolute value of 10 and -10, both will be 10. The sign part is omitted.

  • The absolute value of a complex number, (a + bi) is defined as the distance between the origin (0, 0) and the point (a, b) in the complex plane and the formula is √a² + b²

1. Syntax of abs() method

result = abs( num )

Function parameter

The abs() method takes a required single argument num which can be one of the following types:

  • integer – for example 1, 2, 3, 100, -20, -50, etc.
  • float – for example 1.1, 2.2, 3.2, 100.10, -20.02, -50.05, etc.
  • complex number – for example 1+1j, 2-2j, etc.

Function return value

The return value of abs(), result‘s type and value is depend on the method argument num.

  • When num is integer, result will be an int type and value is absolute value of integer.
  • When num is floating point number, result will be an float type and value is absolute value of floating point number.
  • When num is complex number, result will be an complex type and value is magnitude of the given complex number.

2. Python abs() examples

2.1. Get absolute value of an interger or a float

Python program to get the absolute value of number.

# Some integer value
int_val = -50

print('Type value of -50 is:', type(int_val))
print('Absolute value of -50 is:', abs(int_val))

# Some floating point number
flo_val = -99.99

print('Type value of -99.99 is:', type(flo_val))
print('Absolute value of -99.99 is:', abs(flo_val))

Program output.

Type value of -50 is: <class 'int'>
Absolute value of -50 is: 50

Type value of -99.99 is: <class 'float'>
Absolute value of -99.99 is: 99.99

2.2. Get magnitude of a complex number

Python program to get the magnitude value of a complex number. It can be a float value as well.

# Some complex number
com_val = (5 - 9j)

print("datatype of val_sum:",type(com_val))
print('Magnitude of 5 - 9j is:', abs(com_val))

Program output.

datatype of val_sum: <class 'complex'>
Magnitude of 5 - 9j is: 10.295630140987

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.