user
How to compute absolute value in Python?
alphonsio

The best option to compute the absolute value is to use the built-in abs() function:

y = -3.14
print(abs(y))  # Output: 3.14

In Python, you can compute the absolute value of a number using the built-in abs() function.

Here’s how it works:

# For integers
x = -10
print(abs(x))  # Output: 10

# For floating-point numbers
y = -3.14
print(abs(y))  # Output: 3.14

# For complex numbers
z = 3 - 4j
print(abs(z))  # Output: 5.0   (because √(3² + (-4)²) = 5)

Key points:

  • abs() works for integers, floats, and complex numbers.
  • For complex numbers, it returns the magnitude (distance from origin in the complex plane).

If you’re working with arrays (e.g., using NumPy), you can use numpy.abs() or its alias numpy.absolute():

import numpy as np

arr = np.array([-1, -2, 3])
print(np.abs(arr))  # Output: [1 2 3]