Skip to content

Ceil division with math.ceildiv #90797

Closed
Closed

Description

@VladimirFeinberg
BPO 46639
Nosy @tim-one, @mdickinson, @stevendaprano, @serhiy-storchaka, @nathanielmanistaatgoogle

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields:

assignee = None
closed_at = None
created_at = <Date 2022-02-04.19:25:23.669>
labels = ['type-feature', 'library', '3.11']
title = 'Ceil division with math.ceildiv'
updated_at = <Date 2022-02-08.07:28:32.645>
user = 'https://bugs.python.org/VladimirFeinberg'

bugs.python.org fields:

activity = <Date 2022-02-08.07:28:32.645>
actor = 'serhiy.storchaka'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2022-02-04.19:25:23.669>
creator = 'Vladimir Feinberg'
dependencies = []
files = []
hgrepos = []
issue_num = 46639
keywords = []
message_count = 12.0
messages = ['412527', '412541', '412580', '412583', '412590', '412593', '412594', '412751', '412780', '412803', '412814', '412815']
nosy_count = 6.0
nosy_names = ['tim.peters', 'mark.dickinson', 'steven.daprano', 'serhiy.storchaka', 'Nathaniel Manista', 'Vladimir Feinberg']
pr_nums = []
priority = 'normal'
resolution = None
stage = None
status = 'open'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue46639'
versions = ['Python 3.11']

Activity

  1. stevendaprano commented on Feb 8, 2022

    @stevendaprano
    Member

    Decimal is a good question.

    Why does floor division not do floor division on Decimal? The
    documentation says

    The integer division operator // behaves analogously, returning the 
    integer part of the true quotient (truncating towards zero) rather 
    than its floor, so as to preserve the usual identity 
    x == (x // y) * y + x % y
    

    but it's not clear why that identity is more important than floor
    division returning the floor.

    I guess we could just document the difference and maybe add a
    Decimal ceildiv method, although that makes me sad :-(

    Could we "fix" Decimal?

  2. tim-one commented on Feb 8, 2022

    @tim-one
    Member

    The decimal module intends to be a faithful implementation of external standards. The identity

    x == (x // y) * y + x % y

    isn't a minor detail, it's the dog on which all else is but a tail ;-)

    It's why Guido picked -7 // 4 = -2 in Python[1]. That's really not all that useful on its own, and does surprise people. But it's necessary so that the identity implies -7 % 4 = 1, and _that's_ what drove it all, the desire that doing mod wrt a positive int always give a non-negative result.

    The identity also implies that, under truncating division, mod returns a result with the sign of the dividend rather than of the divisor.

    decimal implements what the external standards demand integer division do, and also integer modulus. The decimal context divmod() method returns both at once.

    The behavior of int div and mod are linked by all standards I'm aware of, including by C89 (which didn't define what integer division did in all cases, but did demand that - whatever it did - % had to work in a way consistent with the named identity).

    [1] http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

  3. serhiy-storchaka commented on Feb 8, 2022

    @serhiy-storchaka
    Member

    Round division would be useful not less than ceil division, if not more. In the stdlib it would be used in:

    1. The datetime module.
    2. Fraction.__round__.
  4. transferred this issue fromon Apr 10, 2022
  5. mdickinson commented on Apr 11, 2022

    @mdickinson
    Member

    I'm going to close this here. Like every other design decision it's a trade-off. Both the benefit and the cost are small, but to my eyes the cost outweighs the benefits here.

  6. mdickinson commented on Nov 5, 2025

    @mdickinson
    Member

    @serhiy-storchaka Is it worth re-opening/re-considering this issue now that there's a more obvious place to put a ceildiv function?

    One wrinkle - in the place I most recently found myself wanting a ceildiv operation, I was actually working with datetime.timedelta objects rather than integers (or floats). That is, I was doing something along the lines of:

    >>> import datetime
    >>> video_length = datetime.timedelta(minutes=59)
    >>> max_analysis_length = datetime.timedelta(minutes=10)
    >>> analysis_count = -(video_length // -max_analysis_length)
    >>> analysis_count
    6

    and I wanted to be able to spell that fourth line as analysis_count = ceildiv(video_length, max_analysis_length).

    So if ceildiv got added to math.integer, would it break the math.integer module policy to have it accept timedelta objects as well as ints? What about accepting floats?

  7. mdickinson commented on Nov 5, 2025

    @mdickinson
    Member

    So if ceildiv got added to math.integer, would it break the math.integer module policy to have it accept timedelta objects as well as ints? What about accepting floats?

    Maybe worth noting that other similarly type-generic functions (math.prod, math.sumprod) are still in math, not math.integer.

  8. serhiy-storchaka commented on Nov 5, 2025

    @serhiy-storchaka
    Member

    It is easier to implement ceildiv and friends only for integers (_PyLong_DivmodNear only supports integers), but it would be more convenient if they are general, applicable to floats, decimals, fractions. Should we add two variants -- integer-only and general?

    And if add ceildiv, we need to add also variants with rounding to the nearest integer, to zero, to infinity, and corresponding divmod variants.

    We have also to keep in mind that in future we may add the rounding option for isqrt() and for future ilog() or ilog2().

    See also #139273. We may need more such complicated code if we want support high-precision timedelta.

  9. tim-one commented on Nov 5, 2025

    @tim-one
    Member

    The only thing that's actually been requested (& more than once) I've seen is ceildiv(int, int). Would it be possible to just start with that, to make some users happy, without making any progress for years on end due to hypothetical "purity" arguments? 😉.

    Python just doesn't need GMP's 18 variations, but GMP is there if people want them. Real Python programmers do want what the OP of this report asked for. It's not at all uncommon in "number theory" work too - int ceiling division is a fundamental primitive.

    Other types can follow later if there's real need demonstrated repeatedly. But it's a pit. For example, timedelta // timedelta returns an int now, but timedelta // int returns a timedelta, and timedelta // float raises TypeError.

    If args aren't int, I'd be fine with falling back to the generic -(x // -y), but special-casing Decimal to raise TypeError instead (since decimal's implementation of __floordiv__ doesn't work for this, and better to refuse to pretend that whatever it does is fine).

  10. serhiy-storchaka commented on Nov 5, 2025

    @serhiy-storchaka
    Member

    I do not remember I even needed ceildiv (perhaps because this was easy to write in other way), but _divide_and_round is not so trivial.

    If you only need integer operations -- I think that the bar to add new functions to math.integer is now lower.

  11. skirpichev commented on Nov 5, 2025

    @skirpichev
    Member

    Lets focus just on ceildiv and friends here. And reopen issue, indeed.

    would it break the math.integer module policy to have it accept timedelta objects as well as ints?

    Certainly yes.

    What about accepting floats?

    For floats, like Decimal's, maybe we have a better option? I.e. support contexts, that will expose FPE status flags and control modes.

    And if add ceildiv, we need to add also variants with rounding to the nearest integer, to zero, to infinity, and corresponding divmod variants.
    We have also to keep in mind that in future we may add the rounding option for isqrt()

    If we are going to support different rounding modes for isqrt(), maybe we should do same for division, instead of bunch of gmpy2-like functions? (Though, for isqrt() I would rather prefer isqrt_rem() as a building block.)

    It seems to me that for division - all three cases from the GMP do make sense (we have feature requests and/or code in the stdlib, which reinvent the wheel). But I'm not sure if we need something beyond the quotient, i.e. c_divmod(), t_mod() and so on. Note also, that MPFR/libmpdec have more rounding modes.

  12. self-assigned this
    on May 8, 2026
  13. removed
    3.11
    on May 8, 2026
  14. skirpichev commented on May 8, 2026

    @skirpichev
    Member
  15. skirpichev commented on May 31, 2026

    @skirpichev
    Member

    I'll close this issue in favor of #76159 (more old). Both asks for support of differently rounded division.

  16. removed their assignment
    on May 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions