In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.
Example:
5/2 gives 2
and
-5/2 gives -3
How to get -2 when I divide -5/2 ?
In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.
Example:
5/2 gives 2
and
-5/2 gives -3
How to get -2 when I divide -5/2 ?
You should enclose division in expression like below
print -(5/2)
As of this accepted answer:
> int(float(-5)/2)
-2
> int(float(5)/2)
2
This happens due to python rounding integer division. Below are a few examples. In python, the float
type is the stronger type and expressions involving float
and int
evaluate to float
.
>>> 5/2
2
>>> -5/2
-3
>>> -5.0/2
-2.5
>>> 5.0/2
2.5
>>> -5//2
-3
To circumvent the rounding, you could leverage this property; and instead perform a calculation with float
as to not lose precision. Then use math module to return the ceiling of that number (then convert to -> int again):
>>> import math
>>> int(math.ceil(-5/float(2)))
-2
You need to use float division and then use int
to truncate the decimal
>>> from __future__ import division
>>> -5 / 2
-2.5
>>> int(-5 / 2)
-2
In Python 3, float division is the default, and you don't need to include the from __future__ import division
. Alternatively, you could manually make one of the values a float to force float division
>>> -5 / 2.0
-2.5
>>> import math
>>> math.ceil(float(-5)/2)
-2.0