5

I see Why is -1/2 evaluated to 0 in C++, but -1 in Python? says integer division rounds towards infinity in Python, namely, floor is applied to the result.

I thought int(value) would also do something like floor, while I get int(-1.5) == -1 in practice, which was expected to be -2 in my mind.

So question is: why rules are inconsistent between integer division and function int()? Is there any reasonable explanation?

Community
  • 1
  • 1
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108

2 Answers2

4

int() removes the decimal component; it doesn't do any rounding. From the documentation:

If x is floating point, the conversion truncates towards zero.

For turning a float into an int this is entirely logical behaviour. This is not division, flooring or otherwise.

The // floor division operator otherwise clearly does floor, not truncate. In Python 2, for two integer operands, the / division also floors. The documentation again:

the result is that of mathematical division with the ‘floor’ function applied to the result

where math.floor() is documented as:

Return the floor of x as a float, the largest integer value less than or equal to x.

I see no inconsistency here; division floors, turning floats to integers truncates.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Maybe it's not inconsistent with the docu, but why should it be desirable? I get int(-1.0/49*49) = 0, but int(-1.0/50*50) = -1. Any reason why int() should not do rounding? – maxy Apr 15 '14 at 09:10
  • There is an explicit [`round()` function](https://docs.python.org/2/library/functions.html#round) for rounding. `int()` explicitly takes the integer part of the float value, it doesn't round. It's a different operation. – Martijn Pieters Apr 15 '14 at 14:59
0

Maybe round() with ndigits = 0 is more close to what you're expecting. But round() doesn't return an integer, but a float: see the documentation

kronwiz
  • 193
  • 7