You will spot a difference when using floats:
>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000
floor returns an integer. For most cases 1000 and 1000.0 are equivalent, but not always.
You will spot a difference when using floats:
>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000
floor returns an integer. For most cases 1000 and 1000.0 are equivalent, but not always.
math.floor(N)returns an int, andN // 1returns a float.>>> type(math.floor(-4.4)) <class 'int'> >>> type((-4.4) // 1) <class 'float'>Because of this
floor(nan)will raise ValueError whilenan // 1returns NaN (similar for ±inf.)>>> math.floor(math.nan) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot convert float NaN to integer >>> math.nan // 1 nan
I don't think there are other differences when N is a float, since x//y is defined as ⌊x/y⌋.
Videos
Hello, Can someone please explain the me the difference between those two arithmetic signs because am new to programming python:)
floor() rounds down. int() truncates. The difference is clear when you use negative numbers:
>>> import math
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3
Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.
Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.
I tested similar time complexity of both methods.
from time import time
import math
import random
r = 10000000
def floorTimeFunction():
for i in range(r):
math.floor(random.randint(-100,100))
def intTimeFunction():
for i in range(r):
int(random.randint(-100,100))
t0 = time()
floorTimeFunction()
t1 = time()
intTimeFunction()
t2 = time()
print('function floor takes %f' %(t1-t0))
print('function int takes %f' %(t2-t1))
Output is:
# function floor takes 11.841985
# function int takes 11.841325
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