1

I am coding this in python:

1 / -2

The result is not 0 but -1, I am confused. why is python designed this way? What's the logic behind it?

I am using python 2.7.6

richard.g
  • 3,585
  • 4
  • 16
  • 26
  • Why would you expect 0 rather than -1? – Oliver Charlesworth Mar 23 '14 at 12:50
  • possible duplicate of [Integer division & modulo operation with negative operands in Python](http://stackoverflow.com/questions/14348219/integer-division-modulo-operation-with-negative-operands-in-python) – devnull Mar 23 '14 at 13:17

1 Answers1

7

Guido himself explains it here: http://python-history.blogspot.co.uk/2010/08/why-pythons-integer-division-floors.html.

Relevant snippet:

there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship:

a/b = q with remainder r

such that

b*q + r = a and 0 <= r < b

...

Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680