richard.g
richard.g

Reputation: 3765

Problems of dividing by a negative number in python

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

Upvotes: 1

Views: 85

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272822

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.

Upvotes: 7

Related Questions