Understanding the result of modulo operator: %%

I'll offer another explanation. Take this problem:

20 %% 10 = 0

Instead of evaluating the modulo, start with simple divison:

20 / 10 = 2

As you know, the answer "2" means that it takes two sets of 10 to get 20. Note that we can also write the answer this way with the decimal, 2.0.

The decimal is important. When the decimal is .0, we have no remainder. We have complete sets. If division yields a 0 decimal, then the modulo evaluates to zero.

Now consider this:

11/3 = 3.667

That tail part, the 0.667, is the portion of a set of 3 that remains after we form all full sets of 3 that we can. On the left side of the decimal, we show:

#Splitting the answer into its components - 3 full sets, 0.667 partial sets
3.0 + 0.667 = 3.667

So if we want to know the actual remaining quantity, we can multiply 0.667 by the divisor, 3:

0.667 * 3 = 2

This is the remainder. It is the quantity that remains after all full sets of 3 are formed. It's the same result we get using modulo:

11 %% 3 = 2

The same applies here. Given this problem,

10 %% 20 = 10

we can divide normally and get:

10 / 20 = 0.5

Reading this out, we have 0 full groups of 20 (left side); we only have half a set, 0.5, of 20.

0.5 * 20 = 10

This is equivalent to:

10 %% 20 = 10

10 is thus the remainder. It's the gap between the 10 we have and the 10 we need to get to 20.


I was also very confused, but if you understand that the result of the %% operator is the REMAINDER of a division, it is very easy.

Eg. 75%%4 = 3

and I noticed if the dividend is lower than the divisor, then R returns the same dividend value.

Eg.

4%%75 = 4
10 %% 20  = 10
2 %% 8  = 2

division parts


Nothing wrong:

10 = 1 * 10 + 0
20 = 2 * 10 + 0
10 = 0 * 20 + 10
2  = 0 * 8  + 2 

The modulo is the number after +.


In general, for two numbers a and b, there is

a = floor(a / b) * b + (a %% b)

Let's write a toy function:

foo <- function(a,b) c(quotient = floor(a / b), modulo = a %% b)

foo(10, 10)
#quotient   modulo 
#   1        0 

foo(20, 10)
#quotient   modulo 
#   2        0 

foo(10, 20)
#quotient   modulo 
#   0       10 

foo(2, 8)
#quotient   modulo 
#   0        2 

Update: Instead of using floor(a / b) to get quotient, we can also use a %/% b.

Tags:

Operators

R