27

I need to ceil and floor 3/2 result (1.5) without using import math.

math.floor(3/2) => 3//2 math.ceil(3/2) => ?

OK, here is the problem: to sum all numbers 15 + 45 + 15 + 45 + 15 ... with N items.

sum = (n//2) * 5 + int(n/2) * 15

zooks
  • 438
  • 1
  • 4
  • 11
  • wrong result for 4/2 – zooks Sep 14 '15 at 07:03
  • 2
    Why not just use the `math` library? – Ffisegydd Sep 14 '15 at 07:05
  • 1
    for education purposes – zooks Sep 14 '15 at 07:06
  • Believe me, I tried. BTW I used PHP before, now I'm learning Python :) – zooks Sep 14 '15 at 07:12
  • 2
    Use the ceiling division operator, `--0--`! This converts floor division to ceiling division. For example, `--0-- 3//2` gives the ceiling of `3/2`. Try it if you don't believe me! (Okay, so you could spell it without the leading `--`, but it looks better with it.) – Mark Dickinson Sep 14 '15 at 07:16
  • @Ffisegydd: There's at least one good reason to avoid the math library here, which is that by going via floating-point you can lose precision (and get the wrong answer as a result). – Mark Dickinson Sep 14 '15 at 07:20
  • @zooks: More seriously, use the fact that `ceiling(x)` == `-floor(-x)` for any real number `x`. – Mark Dickinson Sep 14 '15 at 07:21
  • Does this answer your question? [Is there a ceiling equivalent of // operator in Python?](https://stackoverflow.com/questions/14822184/is-there-a-ceiling-equivalent-of-operator-in-python) – user202729 Oct 01 '21 at 12:33

5 Answers5

54
>>> 3/2
1.5
>>> 3//2 # floor
1
>>> -(-3//2) # ceil
2
xyres
  • 18,466
  • 3
  • 49
  • 80
bakar
  • 932
  • 2
  • 10
  • 19
  • 3
    funny that `>>>math.ceil(4.0000000000000001/2)` is 2, but `>>>math.ceil(4.000000000000001/2)` is 3 – soshial Dec 29 '17 at 13:00
  • But not surprising, when you consider that `4.0000000000000001 == 4.0` is `True` but `4.000000000000001 == 4.0` is False – FiddleStix Dec 17 '21 at 12:15
9

Try

def ceil(n):
    return int(-1 * n // 1 * -1)

def floor(n):
    return int(n // 1)

I used int() to make the values integer. As ceiling and floor are a type of rounding, I thought integer is the appropriate type to return.

The integer division //, goes to the next whole number to the left on the number line. Therefore by using -1, I switch the direction around to get the ceiling, then use another * -1 to return to the original sign. The math is done from left to right.

James Barton
  • 91
  • 1
  • 3
4

Try:

def ceil(n):
    res = int(n)
    return res if res == n or n < 0 else res+1

def floor(n):
    res = int(n)
    return res if res == n or n >= 0 else res-1
acw1668
  • 30,224
  • 4
  • 17
  • 30
1

I know this is old...but you can call those like this too:

>>> (3/2).__ceil__()
2
>>> (3/2).__floor__()
1
farhan778
  • 11
  • 1
  • 2
0

try it like:

if a%b != 0:
  print(int(a//b + 1))
else:
  print(int(a/b))