2

All our mathematics books have been teaching us that a remainder is always positive. Wiki tells me that a remainder can be a least positive remainder or a least absolute remainder. It is a pretty basic concept which can be very difficult to unlearn for a lot people(including me). It could be cause of weird bugs when a programmer is working with multiple languages.

What is the reason behind erlang redefining such a basic concept?

Eshell V6.2 (abort with ^G) 1> -5 rem 3. -2

This result is not consistent with either of Least Positive Remainder or Least Absolute Remainder Concept.

http://en.wikipedia.org/wiki/Remainder#Integer_division

user2244221
  • 167
  • 2
  • 8
  • 2
    Computer scientists are not mathematicians, and they both have completely different attitudes. The erlang language designers probably felt this was more pragmatic. – yxre Dec 05 '14 at 08:31

1 Answers1

5

It is because integer divisions are rounded towards 0.

It happens in many other programming languages, for example see this answer about C.


Indeed if you consider the division as being defined before the % operation, then we still expect
a = (a / b) * b + (a % b). It then comes naturally that

  • 5 / 3 = 1, so 5 % 3 == 2
  • -5 / 3 = -1, so 5 % 3 == -2

If we rounded toward -infinity instead of towards 0, then -5/3 would be -2, and % would be the modulus operator. Right now it is just a remainder of the division.

Community
  • 1
  • 1
Cimbali
  • 11,012
  • 1
  • 39
  • 68