Issue
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?
Solution
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 supports Monica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.