commodorejohn wrote:
(Is there a canonical "correct" answer for whether the sign of the remainder should change? I can't recall.)
It's complicated.
The properties that you almost always want are
- (a/b)*b + (a%b) = a
- abs(a%b) < abs(b)
It can also be nice to have
- abs(a/b) = abs(a)/abs(b)
- sign(a%b) = sign(b)
but unfortunately you can't have both.
Some languages provide two remainder operations, with the sign of the remainder being the sign either of the dividend or the divisor, letting people choose which properties are more important to them. In VHDL, you get
Code:
10 / 3 = 3
10 mod 3 = 1
10 rem 3 = 1
-10 / 3 = -3
-10 mod 3 = 2
-10 rem 3 = -1
10 / -3 = -3
10 mod -3 = -2
10 rem -3 = 1
-10 / -3 = 3
-10 mod -3 = -1
-10 rem -3 = -1
rem is the remainder of a division that rounds towards zero (so 10/-3 = -3) and mod is the remainder of a division that rounds towards negative infinity (so 10/-3 = -4). There might some specialised mathematical languages that provide both of these division operators, but I don't know any - even though VHDL provides both remainders, it has only the one divide. Usually you only get one divide and one remainder, and they're both the "round towards zero" flavour.