Taking modulo of a negative number is a bit more complex mathematics which is done behind the program of Python. If we don’t understand the mathematics behind the modulo of negative number than it will become a huge blender.
Mathematics behind the negative modulo :
Let’s Consider an example, where we want to find the
-5%4. You all must be wondering that the answer will be according to the below rule –
-5/4 = 1.25 and math.floor(-1.25) = -2
But this is not the anser we get, when we’ll run the above code we’ll get the answer as 3. This is because Python’s modulo operator (%) always return a number having the same sign as the denominator. What happens behind the scene is that Python applies the distribute law of Modulo operator which is –
(a+b)mod n = [(a mod n)+(b mod n)]mod n
To apply this math Python break the given statement as –
-5%4 = (-2*4 + 3) % 4 = 3
This was done so that the (-2*4)%4 will give the answer as 0 (as we are always getting a multiple of divisor as our first number) and the overall result will be 3. Let’s see more examples for better understanding.
-3 % 7 = ( -1*7 + 4 ) % 7 = 4
-5 % 2 = (-3*2 + 1) % 2 = 1
Example #1 :
In this example we can see that by using this mathematics, we are able to perform and understand the negative modulo.
Example #2 :
- Python | Filter the negative values from given dictionary
- Python | Perform operation on each key dictionary
- Python | Perform append at beginning of list
- Python Program to perform cross join in Pandas
- perform method - Action Chains in Selenium Python
- Python | Visualize missing values (NaN) values using Missingno Library
- Python - Extract Unique values dictionary values
- Python - Remove duplicate values across Dictionary Values
- Python - Lists Modulo
- Python | K modulo on each Dictionary Key
- Python | Modulo K List
- Python | Nested Records Modulo
- Python - Modulo of tuple elements
- Python | Maximum modulo pair
- Python - Modulo K elements removal
- numpy.negative() in Python
- Python - tensorflow.math.negative()
- Python | Rearrange Positive and Negative Elements
- Negative transformation of an image using Python and OpenCV
- Python - Remove Negative Elements in List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.