Just randomly tried out this:
>>> int(-1/2)
-1
>>> int(-0.5)
0
why the results are different??
Just randomly tried out this:
>>> int(-1/2)
-1
>>> int(-0.5)
0
why the results are different??
Try this:
>>> -1/2
-1
>>> -0.5
-0.5
The difference is that integer division (the former) results in an integer in some versions of Python, instead of a float like the second number is. You're using int
on two different numbers, so you'll get different results. If you specify floats first, you'll see the difference disappear.
>>> -1.0/2.0
-0.5
>>> int(-1.0/2.0)
0
>>> int(-0.5)
0
The difference you see is due to how rounding works in Python. The int()
function truncates to zero, as noted in the docs:
If x is floating point, the conversion truncates towards zero.
On the other hand, when both operands are integers, the /
acts as though a mathematical floor operation was applied:
Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.
So, in your first case, -1 / 2
results, theoretically, in -0.5
, but because both operands are ints, Python essentially floors the result, which makes it -1
. int(-1)
is -1
, of course. In your second example, int
is applied directly to -0.5
, a float, and so int
truncates towards 0, resulting in 0
.
(This is true of Python 2.x, which I suspect you are using.)
This is a result of two things:
Negative integer division surprising result
http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html
Force at least one number to float, and the results will no longer surprise you.
assert int(-1.0/2) == 0
As others have noted, in Python 3.x the default for division of integers is to promote the result to float if there would be a nonzero remainder from the division.
As TheSoundDefense mentioned, it depends upon the version. In Python 3.3.2:
>>> int(-1/2)
0
>>> int(-0.5)
0
int() command truncates towards 0, unlike floor() which rounds downwards to the next integer. So int(-0.5) is clearly 0.
As for -1/2, actually -1/2 is equal to -1! Therefore rounding downwards to the next integer is -1. In Python 2, -a/b != -(a/b). Actually, -1/2 equals floor(-1.0 / 2.0), which is -1.