[New-bugs-announce] [issue46639] Ceil division with math.ceildiv
report at bugs.python.org
Fri Feb 4 14:25:23 EST 2022
New submission from Vladimir Feinberg <vladimirfeinberg at gmail.com>:
I have a request related to the rejected proposal (https://bugs.python.org/issue43255) to introduce a ceildiv operator.
I frequently find myself wishing for a ceildiv function which computes `ceil(x/y)` for integers `x,y`. This comes up all the time when "batching" some resource and finding total consumption, be it for memory allocation or GUI manipulation or time bucketing or whatnot.
It is easy enough to implement this inline, but `math.ceildiv` would express intent clearly.
# x, y, out: int
out = math.ceil(x / y) # clear intent but subtly changes type, and also incorrect for big ints
out = int(math.ceil(x / y)) # wordy, especially if using this multiple times, still technically wrong
out = (x + y - 1) // y # too clever if you haven't seen it before, does it have desirable semantics for negatives?
out = -(-x//y)
def ceildiv(a: int, b: int) -> int: # Clearest and correct, but should my library code really invent this wheel?
out = ceildiv(x, y)
Even though these are all "one-liners", as you can see leaving people to complex manually-implemented `ceildiv`s might result in bugs or unclear handling of negatives.
components: Library (Lib)
nosy: Vladimir Feinberg
title: Ceil division with math.ceildiv
versions: Python 3.11
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce