[Tutor] Division by negative numbers [was: no subject]
steve at pearwood.info
Sat Jun 2 15:11:14 CEST 2012
Jason Barrett wrote:
> In python, why does 17/-10= -2? Shouldn't it be -1?
Integer division with negative numbers can be done in two different ways.
(1) 17/-10 gives -1, with remainder 7.
Proof: -1 times -10 is 10, plus 7 gives 17.
(2) 17/-10 gives -2, with remainder -3.
Proof: -2 times -10 is 20, plus -3 gives 17.
[Aside: technically, integer division with positive numbers also has the same
choice: 17 = 1*10+7 or 2*10-3.]
Every language has to choose whether to support the first or the second
version. Python happens to choose the second. Other languages might make the
same choice, or the other.
For example, C leaves that decision up to the compiler. Different C compiles
may give different results, which is not very useful in my opinion.
Ruby behaves like Python:
steve at orac:/home/steve$ irb
Other languages may be different.
P.S. in future, please try to include a meaningful subject line to your posts.
More information about the Tutor