How to Use the abs() Function in Python

The abs() function is a fundamental part of Python’s math module, helping you find the absolute value of any number. Whether you’re working with integers, floating points, or complex numbers, abs() can handle these all data types, and understanding it can save you time.


What is the abs() Function in Python?

The abs() function in python returns the absolute value of a number, meaning it strips the number of its sign. For positive numbers, it returns the number as-is. For negative numbers, it converts them to positive. In case of complex numbers, it returns their magnitude.

The magnitude of a complex number is the distance from the origin to the complex number on the complex plane. It is also known as the modulus.


Syntax

abs(number)

number can be:

  • An integer (int)
  • A floating-point (float)
  • A complex number (3 + 4j)

How Does abs() Work with Different Data Types?

1. Integers and Floats

For integers and floats, abs() simply returns the positive value of it.

print(abs(-5))   # Output: 5
print(abs(2.34))  # Output: 2.34

2. Complex Number

For complex numbers, abs() calculates the magnitude using the formula.

complex_num = 3 - 4j
print(abs(complex_num))  # Output: 5.0

This is how you can use the abs() function in python at ease to get an absolute value.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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