Introduction of Python abs() function
abs() is one of Python built-in functions. Python abs() function returns the absolute value of any number.
What is absolute value of a number?
Absolute value is the value without any sign (positive or negative sign). its just value regardless of any sign.
Syntax of abs() function
- abs is function name used to get the absolute value.
- any_number is the actual number whose absolute value need to be calculate.
Example of abs () function
Let’s understand Python abs() function by taking example.
abs() function with positive number
#Python abs() function with positive value number=10 print (abs(number))
In above example we have positive number=10, so abs() function will return 10. No change in the output
abs() function with negative number
#Python abs() function with negative value number=-10 print (abs(number))
Here we will see some difference in output as we assign negative number to abs() function, it convert the negative number to number only without any sign.
abs() function with float number
#Python abs() function with float value f1=1.05 print (abs(f1)) f2=-2.05 print (abs(f2))
In Python, abs() with float number will work exactly same as with integer number.
abs() function with complex number
abs() function work something different with complex number in Python. Let’s understand it with simple example.
#Python abs() function with complex value c=3+4j print(abs(c))
You seems surprised here, how output is 5.0 here. you might thinking that output could be 7 or something as (3+4). but abs() function did something else. Let me explain
As we know complex number is something like x+yj, where x and y are real numbers like 0,1,2…9. and j is imaginary number
When abs() function work with complex number in Python, it calculate the value of x+yj as
(x2 + y2 ) 1/2
or we can say squart root of x2 + y2
This is very important point to understand.
In above example, x=3 and y=4, so equation will be (32 + 42 ) 1/2 = (9+16) 1/2 = (25) 1/2 = 5.0
so 5.0 is the answer, here answer is in float number as square root could be in decimal place as we will see in below example
#Python abs() function with complex value c=4+4j print(abs(c))
Here 5.656854249492381 is square root of 32 .
Let’s take one more example
#Python abs() function with complex value c=-4-4j print(abs(c))
Here both x and y are -4 , but output is same 5.656854249492381, because abs() only take magnitude of number not sign that’s why output is same.