4 ms·
> like most languages int() rounds toward zero, and unlike most languages Python division rounds down As someone who only occasionally needs to manipulate pyth
by eric_h 10y ago
> like most languages int() rounds toward zero, and unlike most languages Python division rounds down
As someone who only occasionally needs to manipulate python, and someone who rarely needs to do integer arithmetic on negative numbers (beyond addition/subtraction) this caused me to do a double-take.
I'd always just assumed that languages that treat floats and integers separately would always round integer division towards zero, but TIL python rounds to the left on the number line.
It's really true! Turns out it's true in ruby, too:
-5 / 4 == -2
How 'bout that. Anyone know what other languages treat integer division in this way?
- jacobolus 10y agoIn both cases, b * (a // b) + a % b = a, which is often a behavior that you want. In some other languages, the % operator (IMO wrongly) takes the sign of a, making it more like a “remainder” operator than a “modulo” operator, whereas in Python % (IMO correctly) takes the sign of b. I also agree that this should be thought of as “floor division” rather than “integer division” though.