0

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
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
kilojoules
  • 9,768
  • 18
  • 77
  • 149

2 Answers2

5

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
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62
4

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".

J. Doe
  • 41
  • 2