>>> 3/2
1.5
>>> 3//2 # floor
1
>>> -(-3//2) # ceil
2
Answer from bakar on Stack Overflow>>> 3/2
1.5
>>> 3//2 # floor
1
>>> -(-3//2) # ceil
2
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.
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? - Stack Overflow
what is the difference between using math.ceil and round for rounding the decimal ?
[Python] Not able to round up despite having the Math.ceil function
binary search ceiling and floor of number
Videos
As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.
>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>
You can find more information in PEP 3141.
The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.
Consider: If floor() returned an integer, what should floor(1.0e30) return?
Now, while Python's integers are now arbitrary precision, it wasn't always this way. The standard library functions are thin wrappers around the equivalent C library functions.