Pergunta

Why does -103/100 == -2 but 103/100 == 1 in Python? I can't seem to understand why.

Foi útil?

Solução

Integer division always rounds down (towards negative infinity).

http://www.mathsisfun.com/numbers/images/round-up.gif

Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the floor1 function applied to the result.

http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations

 

This allows for the integer division and modulo (remainder, %) operators to connect nicely through the identity x == (x/y)*y + (x%y).

 

1  floor(x) is the largest integer not greater than x.

Outras dicas

Integer division takes (I believe) the floor() of whatever float comes out, more or less.

So that's -2 for the first division and 1 for the second.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top