Tim Smith
9/14/2006 2:57:00 AM
In article <44DBA9B0.8060601@qwest.com>,
"Daniel Berger" <Daniel.Berger@qwest.com> wrote:
> Basically, I'm trying to figure out the nuances of Bignum#remainder vs
> Bignum#modulo. To confuse myself even further K&R (2nd ed, p. 41) says you
Well, one difference seems to be how they handle negative numbers (and
it seems to work the same way for regular sized number, not just
Bignums). Consider dividing -12 by 5.
A mathematician would see this as -12 = 5 * (-3) + 3, so would say that
-12/5 is -3 with a remainder of 3, and would also say that (-12)%5 is 3.
For some reason, the people who design processor instruction sets seem
to think that -12/5 should be -2, not -3. I think their reasoning is
that (-a)/b should equal -(a/b). To make that work, they need to use
round-toward-zero, and that means they see -12 as 5 * (-2) + (-2), so
-12/5 is -2 with a remainder of -2, and (-12)%5 is -2.
Languages like C tend to do whatever the processor does, so in C you get
(-12)%5 coming out -2.
Perl, Ruby (and I think Python) go with the mathematician's view for %.
Ruby goes the other way for remainder, which is an interesting choice.
I suppose it kind of makes sense, because otherwise, why have a separate
remainder method?
I haven't checked to see what any of these do when the divisor, rather
than or in addition to the dividend is negative.
--
--Tim Smith