Python abs() – Absolute Value of a Number

Python abs() function returns the absolute value of the specified number as the method argument.

  • 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 the distance from zero that will always be positive.
    For example, the absolute value of 10 and -10, both will be 10. The sign part is omitted.
  • If the given number is a complex number, method abs() returns its magnitude. 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() Function

result = abs( num )

Function Parameter

The abs() 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 depend on the method argument num.

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

2. Python abs() Example

2.1. Get Absolute Value of an Integer or a Float

Python program to get the absolute value of a 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 !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.