In my application I encountered the following and was surprised by the results:
8/-7=-2
(both integers).
what does this means?
In my application I encountered the following and was surprised by the results:
8/-7=-2
(both integers).
what does this means?
For the actual values, i.e.
8.0/(-7.0)
, the result is roughly-1.143
.Your result using integer division is being rounded down toward the more negative value of
-2
. (This is also known as "Floor division")This is why you will get the somewhat perplexing answers of:
Note: This is "fixed" in Python 3, where the result of
8/(-7)
would be-1.143
. So if you have no reason to be using Python 2, you should upgrade. ;)In Python 3, if you still want integer division, you can use the
//
operator. This will give you the same answer as8/(-7)
would in Python 2.Here's a Python Enhancement Proposal on the subject: PEP 238 -- Changing the Division Operator
In python,
/
operator is for integer division. You can look at it as float division followed by afloor
operation.For example,
Python always does the "floor division" for both negative numbers division and positive numbers division.
That is
But sometime we need 1/-10 to be 0
I figure out it can be done by using the float division first then cast result to int, e.g.
That works fine for me, no need to import the future division or upgrade to Python 3
Hope it can help you~
When both values are integers when dividing Python uses Floor division.
to have python automatically convert integer division to float, you can use:
now:
this feature is not in the standard python 2 not to break existing code that relied on integer division. However, this is the default behavior for python 3.