Hacker News new | ask | show | jobs
by OscarCunningham 849 days ago
Yes that makes perfect sense. So why is int(-1.5) == -1? It should be -2.
3 comments

There is math.floor for rounding towards negative infinity, which has the advantage of being crystal clear.
The same reason int(-1.999) is -1; The operation is different to integer division. I think of it as taking the "integer" part of the float.
As the article mentions, this is called truncation. It truncates (cuts off) the value at the decimal point.
because it's a float and not an int, it's strictly talking about integers here, not floats. All int conversions of floats are converted by discarding the remainder afaik but I could be wrong here (e.g. int(1.9) == 1, and int(-1.9) == -1)

edit: -3//2 == -2 for instance, since it's strictly integer division

It's a valid criticism: By the principle of least surprise, one should strive for a//b = int(a/b).

Basically, there's no free lunch. Personally, I prefer truncating integer division in combination with a pair of remainder operators.

Inspired by Monty Python, the surprises are part of the charm. ¯\_(ツ)_/¯