Absolute Value in Python Explained

Posted in Python on January 20, 2023 by Jessica Rose ‐ 2 min read

Absolute Value in Python Explained

10xer.co Ad Sponsored

β“˜ Sponsored by 10xer.co

In this Tutorial, we’ll figure out what the absolute - abs() function is used for.

For example, let’s consider the absolute value of the number -100:

print(abs(-100))

Output:

100

In Python, the abs() method is a built-in function that returns the absolute value of a number.

The absolute value of a number is its distance from zero on the number line, regardless of whether the number is positive or negative.

For example, the absolute value of -5 is 5, and the absolute value of 5 is also 5.

The absolute value of number X is denoted with |X|, such that:

  • |X| = X —> X is a positive number.
  • |-X| = X —-> X is a negative number.

Example,

* |100| = 100  --->  X is a positive number.
* |-100| = 100  ----> X is a negative number.


Number-line

How to find the absolute value of a number in Python :

Python provides an easy built-in function abs() to find the absolute value.

All you need to write the number with the (n) and the absolute value is returned.

For example :


print(abs(-12314.214))

Output:

12314.214

Example Problem: Given a list of numbers, convert the array into an absolute array

Solution

We can use the abs() function to find the absolute value.

nums = [10, -2315, 12312, -1055, -12316, -12012410, -3.141, 121421]
for n in nums:
    print(abs(n))

Output:

10
2315
12312
1055
12316
12012410
3.141
121421

10xer.co Ad Sponsored

β“˜ Sponsored by 10xer.co

Absolute Value of Complex Number

Complex numbers are composed of both real and imaginary components, making it more challenging to determine their absolute value compared to integers. To find the absolute value of a complex number represented as x + iy, one must use a different approach.

z = x+iy

The absolute value of z will be;

|z|= √[Re(z)2+Im(z)2]

|z| = √(x2+y2)

Where x and y are the real numbers.

__abs__() : is a form of overriding, for abs() method explained in the article : abs() Method in Python

Conclusion

To determine the absolute value of a number in Python, utilizing the built-in abs() method.

Simply pass the number in question as an argument to the function. This method can be applied to both real and imaginary numbers, making it a versatile tool for a variety of mathematical calculations.


10xer.co Ad Sponsored

β“˜ Sponsored by 10xer.co