Python abs()

In this post, we will see about Python abs() method.
Python abs() method returns absolute value of passed number.You can pass int,float or complex number to the abs method.


Syntax


Return

abs returns the value based on the argument.
int: It returns absolute value of int for int argument
float: It returns absolute value of float for float argument
Complex numbers: It returns magnitude of complex number for complex number arguments


Example

Let’s see a very simple example:

num= -23 print("Absolute value of -23 is ",abs(num)) floatNum= -12.657 print("Absolute value of -12.657 is ",abs(floatNum)) complexNum=2-3j print("Absolute value of 2-3j is ",abs(complexNum))

Output:

Absolute value of -23 is 23
Absolute value of -12.657 is 12.657
Absolute value of 2-3j is 3.605551275463989

How did we get 3.605551275463989 for complex number 2-3j.
Magnitude of complex number is calculated as below

complexNum=2-3j print("Absolute value of 2-3j is ",abs(complexNum)) #formula to calculate magnitude (a**2+b**2)**0.5 magnitudeComNum=(2**2+3**2)**0.5 print("Magnitude value of 2-3j is ",magnitudeComNum)

Output:

Absolute value of 2-3j is 3.605551275463989
Magnitude value of 2-3j is 3.605551275463989

As you can see both returns same value.
That’s all about Python abs function.

Leave a Reply

Your email address will not be published. Required fields are marked *