# Why does -22 / 10 return -3?

It’s primarily driven by the desire that i%j have the same sign as j. If you want that, and also want:

`i == (i/j)*j + (i%j)`

then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate i/j need to make i%j have the same sign as i.

There are few real use cases for i%j when j is negative. When j is positive, there are many, and in virtually all of them it’s more useful for i%j to be >= 0. If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite.

CATEGORY: programming

Comment:

This answer is correct and succinct, two excellent qualities. But, at the expense of succinctness, I think it might be good to give a bit more background material for the less mathematically inclined. For example:

Whenever an integer division has a non-integer result, that result must be either truncated or rounded to the "best" representative integer. People who are used to the result of 28/20 being truncated to 2 rather than rounded to 3 may assume that the interpreter truncates toward zero, but for integer math, Python uses the floor function to convert non-integer values to the next lower integer. Truncation toward zero which would make positive numbers smaller and negative numbers bigger.

The primary reason that Python uses the floor function for integer division actually has more to do with the modulo or remainder operator (%) rather than the division operator itself. These two operators are intimately bound by the desire that the language support this invariant:

```   i == (i/j)*j + (i%j)
```
To make this always be true, then for the example of -22 / 10, we could either have:
```    -22 / 10 == -2 and -22 % 10 == -2
```
or we could have:
```    -22 / 10 == -3 and -22 % 10 == 8
```
(Then reuse the original last paragraph from the article.)

Thanks for doing this!

Posted by (2006-11-04)

Comment:

It might be worth mentioning form __future__ import division

Posted by (2006-11-07)

Comment:

I noticed a couple of grammatical errors in my first comment. I guess I typed it in late at night... The sentence "Truncation toward zero which would make positive numbers smaller and negative numbers bigger." should not have "which" in it, and I think the sentence after this one would read better with "rather than" replaced with "than with". Thanks, Pat

Posted by (2006-11-20)

rendered by a django application. hosted by webfaction.