Integer division to next integer

Question:

As you may know, if you do:

>>> 11/2
# 5

And

>>> 11/2.0
# 5.5

I’d like to get 6 in this case. I tried with:

>>> 11//2
# 5

And

>>> 11//2.0
# 5.0

The last one gives the prev integer. I’d like to get the next integer.
Even is the result is like x.1 I’d like to get (x+1).

How can I do this?

Asked By: Gocht

||

Answers:

Use math.ceil

>>> import math
>>> math.ceil(11/2.0)
6.0
>>>
Answered By: letsc
rounded_up = x // y + bool(x % y)

We add 1 if the division produces a nonzero remainder. This has the benefit of not introducing floating-point imprecision, so it’ll be correct in extreme cases where math.ceil produces the wrong answer.


We can also perform the operation with floor division and two negations:

rounded_up = -(-x // y)

The floor of -x/y is the negative of the ceiling of x/y, so negating again produces the ceiling of x/y. Again, we avoid floating-point rounding error by performing all operations in integer arithmetic.

Answered By: user2357112

Generally more efficient than doing both modulus and division work, it’s easy to convert floor division:

x // y

into ceil division (and unlike using math.ceil, it runs no risk of getting incorrect results due to floating point imprecision for large values):

(x + y - 1) // y

If x is exactly divisible by y, then adding y - 1 changes nothing; the floor division makes the end result unchanged. If it’s not evenly divisible, this increases it above the next multiple, getting you ceil division with only a single division operation instead of two (division is expensive; doing it twice is doubly expensive), and no floating point precision issues.

The above doesn’t work for negative y, but there is a solution that does work for it (at the expense of appearing more magical):

-(-x // y)

By flipping the sign on x first, you change the rounding behavior to work in the opposite direction after flipping the sign again at the end. So for x == 5 and y == -2, this second solution produces -2 (the ceiling of -2.5) correctly. It’s typically more efficient than the original solution, but it’s not as obvious how it works, so I can’t strictly recommend it over the clearer solution when the divisor is known to be positive.

Answered By: ShadowRanger
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.