Hacker News new | ask | show | jobs
by aimor 846 days 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.
3 comments

Assuming 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)
`int(a/b)` instead of `a//b` (for trunc to zero behavior. especially important when working with c or disassembled code)
You convert to float, divide and then do floor, ceil or whatever.