4 ms·
Yes that makes perfect sense. So why is int(-1.5) == -1? It should be -2.
by OscarCunningham 3y ago
Yes that makes perfect sense. So why is int(-1.5) == -1? It should be -2.
- mmcnickle 3y agoThe 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.
- Izkata 3y agoAs the article mentions, this is called truncation. It truncates (cuts off) the value at the decimal point.
- consp 3y agobecause 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
- cygx 3y agoIt'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.
- odyssey7 3y agoInspired by Monty Python, the surprises are part of the charm. ¯\_(ツ)_/¯
- Skeime 3y agoThere is math.floor for rounding towards negative infinity, which has the advantage of being crystal clear.