Thursday, January 30, 2020

Modulo operation in programming languages - differently implemented

Many programming languages support an operation which they call modulo operator and which is often designated by the symbol
    %
Often it is also referred to as the remainder after division.

Only recently I found out that this operation does not behave as one might think. The results differ depending on which programming language you are using.

Before I go into the details I would like to illustrate the difference which shows when using negative numbers.

Example

I want to calculate these two expressions:
 27 % 10
-27 % 10
The result for the second expression will be different depending on the programming language.

C

When you are using this statement in C
printf("%d  %d\n", 17 % 10, -17 % 10 );
you get
7  -7

Python

When you are using this statement in python
print( '{0}  {1}'.format( 17 % 10,  -17 % 10 ) )
you get
7  3

Explanation

modulo as remainder by division

Some programming languages implement modulo as a remainder of division operation. Thus -27 % 10 results in the leftover of -27 when you take away the maximum multiple of 10 , so you are left with -7.

modulo as mathematically correct number

Other programming languages implement modulo as correct in the mathematical sense.
Mathematically modulo is defined as the number which needs to be added to a multiple of the divisor to get to the original.
x = m % n
There must be a number 'a' so that
a * n + x = m
and this condition should be met:
0 <= x < n
In our case:
x = 3
a = -2
=>
a * 10 + x = -2 * 10 + 3 = -17

Conclusion

Since I am not a programming languages expert I can only refer to the interesting Wikipedia article about modulo operations.
This subject is worth knowing if any of your programming efforts involve some number operations.
My personal "watch out" topic is awk programming where the behaviour is non-mathematical like C.

No comments:

Post a Comment