Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why python int() works like this? [duplicate]

Tags:

python

int

Just randomly tried out this:

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

why the results are different??

like image 526
user3645866 Avatar asked Dec 14 '22 21:12

user3645866


2 Answers

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
like image 78
TheSoundDefense Avatar answered Jan 02 '23 02:01

TheSoundDefense


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.)

like image 36
mipadi Avatar answered Jan 02 '23 03:01

mipadi