14

It's basically returning the boxes_needed. 1 box can contain 10 items. So if the items typed by the user is 102 then the code should return 11 boxes.

Is there a way to divide that rounds upwards if there is a non-zero remainder?

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
Newbie_Android
  • 225
  • 2
  • 3
  • 12
  • is this what you want `ceil(10.4)` – The6thSense Oct 23 '15 at 09:34
  • 1
    Use the "convert floor division to ceiling division operator", which is spelled "--0--" Example usage: `--0-- 102//10` -> `11`. (Try it!) ``. More seriously, this is just a disguised variant on Stefan Pochmann's answer, which not only gives the right result for integers but also extends correctly to other number types, like `float` and `Fraction`. – Mark Dickinson Oct 23 '15 at 18:57
  • 1
    For anyone else parsing this: it parses as `- (-0) - (-102)//10`. The same effect can be achieved with `0-- 102//10`. `--102//10` fails because it parses as `(- ( - 102)) // 10`. – rhaps0dy Sep 24 '20 at 11:47

4 Answers4

29

For your use case, use integer arithmetic. There is a simple technique for converting integer floor division into ceiling division:

items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize

Alternatively, use negation to convert floor division to ceiling division:

num_boxes = -(items // -boxsize)
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 1
    I think our lecturer wants us to use this technique rather than using ceil since ceil has not been introduced yet in the lectures. Thanks :) – Newbie_Android Oct 23 '15 at 10:15
  • This answer wasn't very clear to me - probably because the question isn't very clear, maybe this helps clarify what's being shown, using the values for the variable names above, 102 / 10 is 10.2; with integer division, 102 // 10 is 10, but to round upwards to 11 without using the math library or floats then either of the above solutions work, thus both of these will give 11: (102 + 10 - 1) // 10 or -(102 // -10) If you need to see why the -1 is needed, consider what happens for 100 and 101 – Andrew Richards Aug 26 '20 at 21:06
24

Negate before and after?

>>> -(-102 // 10)
11
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
2
from math import ceil

print(ceil(10.3))

11
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
  • 5
    Do not do that! As soon as you use floating point arithmetic you let the inaccuracy devil come in. It will work in normal use cases, but if you begin to use long numbers (more than 48 bits in binary representation) integers cannot be exactly represented by IEE-754 double precision number. – Serge Ballesta Oct 23 '15 at 10:12
  • I will keep that in mind – Newbie_Android Oct 23 '15 at 10:21
0

You can try :

import math
math.ceil( x )
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61