Python abs() function


The abs() function in Python returns the absolute value of a given number. The absolute value of a number is the non-negative value of the number, without regard to its sign. For example, the absolute value of -5 is 5, and the absolute value of 5 is also 5.

Syntax

abs(x)
  • x: A number. This can be an integer, floating-point number, or a complex number.

Return Value

  • If x is a positive number or 0, it returns x itself.
  • If x is a negative number, it returns the positive version of x.
  • If x is a complex number, it returns the magnitude (Euclidean distance from the origin).

Examples

  1. Using abs() with integers:

    print(abs(-10)) # Output: 10 print(abs(10)) # Output: 10
  2. Using abs() with floating-point numbers:

    print(abs(-3.14)) # Output: 3.14 print(abs(3.14)) # Output: 3.14
  3. Using abs() with complex numbers: When used with a complex number, abs() returns the magnitude (modulus) of the complex number, which is the distance of the complex number from the origin in the complex plane.

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

    For a complex number a + bj, the magnitude is calculated as:

    magnitude=a2+b2\text{magnitude} = \sqrt{a^2 + b^2}

    So, for 3 + 4j, it returns 5.0 because:

    32+42=9+16=5\sqrt{3^2 + 4^2} = \sqrt{9 + 16} = 5 ```

Summary

  • The abs() function is used to find the absolute value of an integer or float, or the magnitude of a complex number.
  • It is useful in scenarios where only the magnitude of a value is important, not the sign.