Just accidentally tried this:
>>> int(-1/2) -1 >>> int(-0.5) 0
why are the results different?
Try the following:
>>> -1/2 -1 >>> -0.5 -0.5
The difference is that integer division (first) results in an integer in some versions of Python, rather than swimming, like the second number. You use inton two different numbers, so you will get different results. If you first specify a float, you will see that the difference disappears.
int
>>> -1.0/2.0 -0.5 >>> int(-1.0/2.0) 0 >>> int(-0.5) 0
The difference you see is related to how rounding works in Python. The function int() is truncated to zero , as indicated in the docs:
int()
x , .
, , / , :
/
; " ", .
, -1 / 2 , , -0.5, ints, Python , -1. int(-1), , -1. int -0.5, , int 0, 0.
-1 / 2
-0.5
-1
int(-1)
0
( Python 2.x, , , .)
:
http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html
, .
assert int(-1.0/2) == 0
, Python 3.x float, .
TheSoundDefense, . Python 3.3.2:
>>> int(-1/2) 0 >>> int(-0.5) 0
int() 0, floor(), . , int (-0.5), , 0.
As for -1/2, then actually -1/2 is -1! Therefore, rounding down to the next integer is -1. In Python 2, -a / b! = - (a / b). Actually, -1/2 is equal to floor (-1.0 / 2.0), which is -1.