Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does -103/100 == -2 but 103/100 == 1 in Python?

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

like image 645
frazras Avatar asked Mar 19 '13 22:03

frazras


1 Answers

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.

like image 22
Pavel Anossov Avatar answered Oct 19 '22 00:10

Pavel Anossov