简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM