passerine
passerine copied to clipboard
modulo vs remainder
x % y
passerine:
n % m |
m = 7 |
m = -7 |
---|---|---|
n = 4 |
3 |
1 |
n =-4 |
1 |
3 |
c rust haskell lua js python:
n % m |
m = 7 |
m = -7 |
---|---|---|
n = 4 |
3 |
-1 |
n =-4 |
1 |
-3 |
This behavior is not what I expected. I think the operator %
should behave like it does in other languages.
An operator for what passerine has now is great, but it should be named something else.
That is a good point. In Passerine, %
is the euclidean remainder operator. I guess see this post as to the mathematical justification why.
If we look at a set of integers, modulo N, all integers in that set must be 0 ≤ x < N. For this reason, using %
to take the modulo should return a result within that set. This might not be how it works in other programming languages, and perhaps it might be a good idea to explicit distinguish between the different types of modulo, remainder, etc. that can happen. I guess the question of whether the euclidean remainder operator is a good default for %
is up for debate. On one hand, I'd like there to be some cross-language familiarity, but on the other hand, I'd like the operator to be correct within the context of the definitions we've defined.
I suggest it's kinda safe to follow Haskell in this regard, there both quot
/ rem
and div
/ mod
are defined and honored equally, as no one pair is more "correct" than the other. For Python, I think Guido didn't realize the other pair is as "nice" mathematically, at http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html
I guess how (%) should behave is better considered together with integer division operator (we have a standard // operator in passerine?) , they should satisfy either "(x quot
y)*y + (x rem
y) == x" or "(x div
y)*y + (x mod
y) == x" at least. Which one to choose is less important but better to be conventional.
Thanks @complyue, I'm glad you brought up the quot
/ rem
and div
/ mod
relationship! Passerine does not have a standard //
integer division operator implemented. I think that div
/ mod
makes the most sense by default.