I saw a twitter post pointing out that -12/10 = -2 in Python. What causes this? I thought the answer should (mathematically) be one. Why does python "literally" round down like this?
>>> -12/10
-2
>>> 12/10
1
>>> -1*12/10
-2
>>> 12/10 * -1
-1
I saw a twitter post pointing out that -12/10 = -2 in Python. What causes this? I thought the answer should (mathematically) be one. Why does python "literally" round down like this?
>>> -12/10
-2
>>> 12/10
1
>>> -1*12/10
-2
>>> 12/10 * -1
-1
This is due to int rounding down divisions. (aka Floor division)
>>> -12/10
-2
>>> -12.0/10
-1.2
>>> 12/10
1
>>> 12.0/10
1.2
This is known as floor division (aka int division). In Python 2, this is the default behavior for -12/10
. In Python 3, the default behavior is to use floating point division. To enable this behavior in Python 2, use the following import statement:
from __future__ import division
To use floor division in Python 3 or Python 2 with this module imported, use //
.
More information can be found in the Python documentation, "PEP 238: Changing the Division Operato".