1

I've been using modulo % and i noticed some discrepancy. Can anyone explain why this happens:

# ruby
-123 % 10
> 7

-7 % 10
> 3

Then in Java:

// Java
System.out.println(-123 % 10); // -3
System.out.println(-7 % 10);   // -7
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Matthew
  • 2,035
  • 4
  • 25
  • 48
  • 2
    Because it's not really a modulo, but a remainder operator in Java https://stackoverflow.com/questions/90238/whats-the-syntax-for-mod-in-java – Kayaman Nov 10 '20 at 15:21
  • See this answer https://stackoverflow.com/questions/16073932/ruby-modulo-3-with-negative-numbers-is-unintuitive – Zivojin Milutinovic Nov 10 '20 at 15:25
  • Mathematically the modulo operation `mod n` splits numbers into equivalence classes `[z]` with `z` usually being between 0 and n (excl.). When dealing with negative numbers, you can have negatives with the equality `[-3] == [7]` in the case of `mod 10`. So, mathematically, both can be seen as correct. It is simply the calculation that differs. – Seelenvirtuose Nov 10 '20 at 15:29

2 Answers2

1

It happens because in Java the result of the modulo has the same sign of the dividend. In Ruby it has the same signo of the divisor. From Ruby documentation:

x.modulo(y) means x-y*(x/y).floor

Alternatively you could use the remainder() function that does the same thing.

ThatsSamu
  • 61
  • 7
0

The issue is that Java finds the remainder which is different than the modulo result. Ruby finds the least positive result out of an infinite number. So if you add the modulus (10) to the Java result, they will be the same.

A modulo operation says the for x congruent to m mod(n) there exists an integer k such that x - m = kn

Remainder - -123 % 10 = -3
Modulus - x = -123 % 10 so x + 123 = 10k where k is some integer. so x can be any one of ...,-23, -13, -3 ,7, 17, 27, ...

 
WJS
  • 36,363
  • 4
  • 24
  • 39