Ceil and floor equivalent in Python 3 without Math module?

Question:

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

Asked By: zooks

||

Answers:

>>> 3/2
1.5
>>> 3//2 # floor
1
>>> -(-3//2) # ceil
2
Answered By: bakar

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
Answered By: acw1668

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.

Answered By: James Barton

try it like:

if a%b != 0:
  print(int(a//b + 1))
else:
  print(int(a/b))
Answered By: Emad Al-Dean

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

>>> (3/2).__ceil__()
2
>>> (3/2).__floor__()
1

edit: this is for python 3.9 and above

Answered By: farhan778
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.