Integer math question
Sean Ross
sross at connectmail.carleton.ca
Sat Jan 3 19:42:53 CET 2004
"Frank" <mersmann at szut.uni-bremen.de> wrote in message
news:3987e01c.0401030832.114c6f2a at posting.google.com...
> Hi,
>
> can anybody help with the following problem?
>
> In C++
>
> i = 5 / 10 and
> i = -5 / 10 both have the same result 0.
>
> In python
>
> i = 5 / 10 gives me 0 as expected, but
> i = -5 / 10 gives -1 as result.
>
> Is this a feature or a bug? I remember Delphi gave me the same result as
> C++.
>
> TIA,
> Frank
Using the division algorithm:
Let a,b be integers with b>0. Then there exist unique integers q and r such
that:
a = bq + r and 0<=r<b [1]
If we let a=5 and b=10, then a/b is represented by [1] as
a = bq + r
5 = (10) q + r
... skipping some steps, we find that q=0 and r=5
5 = 10(0) + 5
5 = 0 + 5
5 = 5
LHS = RHS
so, 5/10 = 0 in integer division (with no remainder).
Now, let a = -5 and b = 10
-5 = (10)q + r
If we have q = -1, then
-5 = (10)(-1) + r
-5 = -10 + r
Recall [1] above, 0 <= r < b. r must be nonnegative.
In this case r=5,
-5 = -10 + 5
-5 = -5
LHS = RHS
So, q = -1, and r=5, in which case -5/10 = -1 in integer division (without
remainder).
Suppose we let q=0 for the second problem above. Then
-5 = (10)(0) + r
-5 = 0 + r
-5 = r
or
r = -5
But, by [1], r must be nonnegative. So, we have a contradiction. In which
case we can say that q cannot equal 0 in the algorithm above.
So, I suppose the answer to your question would be,
"This is a feature - Python does it properly, where the others do not."
HTH
Sean
More information about the Python-list
mailing list