# Negativ nearest interger?

Terry Reedy tjreedy at udel.edu
Fri Sep 23 01:14:42 CEST 2011

```On 9/22/2011 7:44 AM, Jussi Piitulainen wrote:
> joni writes:

>> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> ...
>>>>> -7/3
>> -3

In late Python 2 you *can* and in Python 3 you *must* use // rather than
/ to get an int result.

>> -3 are more wrong than -2. Negativ number seems not to round to
>> nearest interger, but the integer UNDER the anwser!! Or?
>> Why?
>
> It simply does not round to the nearest integer. It floors. This has
> nicer mathematical properties. In particular, it allows the remainder
> (notated as "per cent") operation (n % m) to return a number that
> differs from n by a multiple of m ("is congruent to n modulo m").
> These two operations go together.

The Python doc set has a FAQ collection. I recommend you read the
questions for those you might be interested in. In the Programming FAQ:

"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."

--
Terry Jan Reedy

```