Why does python int () work like this?

Just accidentally tried this:

>>> int(-1/2)
-1
>>> int(-0.5)
0

why are the results different?

+4
source share
5 answers

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.

>>> -1.0/2.0
-0.5
>>> int(-1.0/2.0)
0
>>> int(-0.5)
0
+6
source

The difference you see is related to how rounding works in Python. The function int() is truncated to zero , as indicated in the docs:

x , .

, , / , :

; " ", .

, -1 / 2 , , -0.5, ints, Python , -1. int(-1), , -1. int -0.5, , int 0, 0.

( Python 2.x, , , .)

+2

:

  • Python 2.x ;
  • Python "Floored" .

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

, .

assert int(-1.0/2) == 0

, Python 3.x float, .

+2

TheSoundDefense, . Python 3.3.2:

>>> int(-1/2)
0
>>> int(-0.5)
0
+1

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.

+1
source

All Articles