>>> 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.
Videos
If x is a float number that you want to round up to an integer, and you want an integer type result, you could use
rounded_up_x = int(-(-x // 1))
This works because integer division by one rounds down, but using the negative sign before and after doing the division rounds the opposite direction. The int here converts the float result to an integer. Remove that int if you want a floating point value that equals an integer, which is what some programming languages do.
Hat-tip to @D.LaRocque for pointing out that Python's ceil() function returns an integer type.
in Python 3, we have object.__ceil__() that is even called by math.ceil internally,
num = 12.4 / 3.3
print(num)
3.757575757575758
num.__ceil__()
4
Or one can always negate the result of a negated number's floor division (and create a new int object unless a float would do),
int(-(-12.4 // 3.3))
4
Simplest would be.
a//b + bool(a%b)
And just for safety,
b and (a//b + bool(a%b))
Cheers.
-(-a//b)
Perhaps the simplest?
========================
*Edited per @Gilles's comment:
for an integer n,
floor(x)=n for x in [n, n+1)
ceil(y)=n+1 for y in (n, n+1]
So, floor(-y)=-n-1 for -y in [-n-1, -n),
and ceil(y)=-floor(-y)=n+1 for y in (n, n+1]
In Python, floor(a/b) = a//b.
Thus ceil(a/b) = -(-a//b)
in python 2, math.ceil returns float, but I need it returns int, and I also want my code run correctly in python2 and 3. Currently , I define my own ceil function like this
def ceil(float_num):
import sys
if sys.version[0] == '2':
from math import ceil as ceiling
return int(ceiling(float_num))
elif sys.version[0] == '3':
from math import ceil
return ceil(float_num)I am just wondering is there any better solution? just like from __future__ import devision?