It is very often necessary to calculate the modulus of a number in Python. Let’s look at what the modulus of a number is, and how to calculate it. Also, separately we will talk about complex numbers.

Table of Contents

## Number modulus

Often in programming you want to calculate the absolute value of a number. In other words, to discard a sign. **When calculating a modulus there are 3 possible situations**:

- When the number is greater than 0. If you take it modulo, it will not change.
- The modulus of zero is also zero.
- Negative number has no sign. That is, we multiply it by -1.

But this is all true only for real numbers. What then is the modulus of complex numbers? A complex number consists of a real component and an imaginary one. Geometrically this can be represented as two orthogonal axes: real and imaginary. We mark the required point on the coordinate axes. The modulus will be the length of the segment drawn from the origin to this point.

## Calculation

**You can calculate the modulus in the following ways**:

- Using the standard function abs.
- Using the math library function fabs.
- With the function we wrote ourselves.

All of these functions work in both Python 2 and Python 3.

### abs

The abs function is used in Python to calculate the modulus of a number. The result of the function is the same type that the argument was.

a = -10 b = abs(a) print(b) print(type(b)) 10 <class 'int'>

### fabs

You can also use the function fabs from the math library. The library can be connected with `from math import fabs`

.

from math import fabs a = -10 b = fabs(a) print(b) print(type(b)) 10.0 <class 'float'>

### Your solution

If for some reason you have no possibility or desire to use the standard functions, you can write your own solution. For example, you can calculate using the ternary operator.

a = -10 b = a if a > 0 else -a print(b) 10

Based on this condition, let’s make our own function.

def my_abs(a): return a if a > 0 else -a print(my_abs(-3)) 3

## Module of a complex number

We have figured out how to do calculations with real numbers. Now let’s see how to get the modulus of a complex number in the Python programming language. We can’t use the function fabs. If we try to use it, we will get a TypeError for converting a complex number to a real number.

from math import fabs a = -10-2j b = fabs(a) print(b) Traceback (most recent call last): File "main.py", line 3, in <module> b = fabs(a) TypeError: can't convert complex to float

But the conversion can be done with abs.

a = -10-2j b = abs(a) print(b) 10.19803902718557

Or we can write our own function:

from math import sqrt def my_abs_complex(c): return sqrt(c.real**2 + c.imag**2) a = -10-2j b = my_abs_complex(a) print(b) 10.198039027185569

The results are the same. But we still had to connect the math library to calculate the square root.