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?

2 Answers 2

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.

2
  • 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, 2014 at 9:10
  • There is an explicit round() function 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, 2014 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.