4 ms·
What do you do in Python when you want different behavior? Sometimes it's desirable to fix, floor, ceil, or round depending on the situation.
by aimor 3y ago
What do you do in Python when you want different behavior? Sometimes it's desirable to fix, floor, ceil, or round depending on the situation.
- wayvey 3y agoYou convert to float, divide and then do floor, ceil or whatever.
- eugenekolo 3y ago`int(a/b)` instead of `a//b` (for trunc to zero behavior. especially important when working with c or disassembled code)
- orlp 3y agoAssuming a, b are integers, the following answers are exact: def div_floor(a, b): return a // b def div_ceil(a, b): return (a + b - 1) // b def div_trunc(a, b): return a // b if (a < 0) == (b < 0) else -(-a // b) def div_round(a, b): return (2*a + b) // (2*b)