How to perform modulo with negative values in Python

This tutorial will see how to perform the modulo with negative numbers in Python. Modulo/Modular division is the operator in Python denoted by ‘%’. It gives you the remainder after the division of two numbers.

If you consider the modulo operation in C/C++ and Python It is understandable if both the numerator and the denominator are positive or negative. But it creates confusion for one positive and one negative value.

First of all, let’s consider the example:


Output :


Now to understand how the modulo operation works internally we need to break it down.

Now we know that,
Dividend = Divisor * Quotient + Remainder

As modulo returns the remainder of  the division then the formula becomes :
Remainder = Dividend – (Divisor * Quotient)

From the above formula, we know the Dividend and the Divisor so we need to find the Quotient.

To find the quotient we have the operation called floor division. It is symbolled by ‘//’. It rounds off the quotient to the nearest integer and returns it.

So according to the above explanation, the modulo operation can be broken down as :
(a % b) = a – (a // b) * b

If you take the same example and execute the modulo of it in C/C++ then you will get the result as 3, -3, 3, -3 respectively.
From this, we can conclude that the differences between the results are because of the different answers we get by the floor division.
Because In Python the floor division operator rounds off the result to the nearest integer before the result and in C/C++ it rounds off the result to the nearest integer next to the result.

Consider the second operation (-8//5)
The actual answer (-8//5) = -1.6
If you find the answer using the floor division operators (-2 < -1.6 < -1)
In Python, (-8//5) = -2
In C/C++, (-8//5) = -1

Now if you put the above floor division values in the obtained equation of modulo division you can easily notice the difference.

Also, the results of the floor division always have the same sign as that of the denominator in Python.

Also,  refer to Modulo Operator in Python

Leave a Reply

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