>>> 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
In python, I am tasked with finding the floor square root of a number without using any built-in operators or functions. I have no idea how to start this, since using a for loop can only check the integer roots.
ex.
in : 8 out : 2 exp: sqrt(8) = 2.82842..., but floor(2.82842..) = 2
I'm just starting to learn and I wanted to try out the floor() function but it just keeps giving me "NameError: name 'floor' is not defined. Did you mean: 'float'?"
for example I'd tell it to floor(69.69696969) and it would just give me the error above.
Am I doing something wrong?
As long as your numbers are positive, you can simply convert to an int to round down to the next integer:
>>> int(3.1415)
3
For negative integers, this will round up, though.
You can call int() on the float to cast to the lower int (not obviously the floor but more elegant)
int(3.745) #3
Alternatively call int on the floor result.
from math import floor
f1 = 3.1415
f2 = 3.7415
print floor(f1) # 3.0
print int(floor(f1)) # 3
print int(f1) # 3
print int(f2) # 3 (some people may expect 4 here)
print int(floor(f2)) # 3
http://docs.python.org/library/functions.html#int