From: Gunnar Andersson Date: 2001-05-08T06:17:15+09:00 Subject: [ruby-talk:14816] Re: Integer division oddness
>It still seems wrong to me. Which is right? -1 or -2?
>I guess it boils down to whether or not you believe
>that the modulus can be negative.
>
>" -10 / 9
>"
>" For ruby, python and tcl you get: -2!
>" For java, c and gforth you get: -1

This is pretty much off topic but the question seems to be if Ruby "does the
right thing or not" so I'll let it live a little longer.

Consider binary arithmetic and it makes sense. When you have reached the
answer with as many whole bits as possible, remaining "non-whole bits" are
rounded off downwards. The negative value is in two's complement format
so rounding the last bit downwards makes the result more negative than
the "real answer" would be.

Contrast that to a positive number, where rounding a bit downward makes
the number smaller.

Coincidentally, it is also true for the relationship between
divisio! n and "arithmetic shift right" which is usually considered to
be: Shifting right n bits = dividing by 2^n.
If the rightmost bit is 1, i.e. if the number is odd, that bit disappears
off the edge and becomes a rounding error. The result for a negative
number in 2's complement is then one less than you might expect.

For example (decimal) -3/2 is clearly -2, if implemented as -3 shifted
right one bit. For a positive number: 3 shifted right one bit
becomes 1. The extreme case ( (-1 / 2) / 2 ) / 2 is then still
-1 and so on.

Maybe it simply makes sense to define it that way because it fits so well
with the 2's complement representation. Another idea - the
rule of always rounding down, also for two's complement numbers likely
produced the simplest logic for arithmetic circuits and therefore this has
lived on as the correct implementation for computer integer arithmetic

It makes sense for binary arithmetic, so the question! is perhaps if
"integer arithmetic", whatever that is, should be defined this way simply
because of the choice of binary representation of numbers, or in some other,
arbitrarily chosen and later proven (read "mathematical" ;-) way.

Cheers
/Gunnar

---
Gunnar Andersson



_____________________________________________________________
Get Your Own .NU Web Address Now! ---> http://WWW.NUNAMES.NU