Absolute value in Python

0/5 No votes

Report this app

Description

The absolute value of a number is the value without considering its sign. For a real number, the absolute value is also known as the modulus of that number.

For example –

x =-3 y=3

Here the absolute value of both x and y will be 3. Apart from real numbers, an absolute value is also defined for complex numbers, vector spaces, etc and it is closely related to the notions of magnitude, distance, and norms in the various mathematical and physical contexts.

The absolute value in Python

Python provides a built-in function called abs() to find the absolute value of a number. This number can be an integer, float, or complex number. In the case of a complex number, it returns its magnitude.

The syntax of the abs() function is given below.

abs(number)

Return value of abs() function

  • If the passed number is integer this function will return an integer value
  • If the passed number is float the function will return a floating-point value
  • In case it is a complex number the returns its magnitude which is also a float value

Example1:

# Python program to find the absolute value of int and float

num1 = -25
num2 = -10.50
# Print the abolute value of an integer
print(f"The absolute value of {num1} is {abs(num1)}")

# Print the absolute value of a floating point number
print(f"The absolute value of {num2} is {abs(num2)}")

When you execute this program it will produce the given output.

Example 2:

# Python program to find the absolute value of a complex number

num1 = (3+5j)

print(f"The magnitude of the complex number {num1} is {abs(num1)}")

The output of this program is given in the image below.

Conclusion

I hope now you understand what is an absolute value and how to find it in Python for a number. If you have a query then write us in the comments below.

Leave a Reply

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