在 Python3中,int()和 floor()之间的区别是什么?

在 Python 2中,floor()返回一个 float 值。虽然对我来说不是很明显,但是我发现了一些解释来说明为什么使用 floor()返回浮点数是有用的(对于像 float('inf')float('nan')这样的情况)。

但是,在 Python3中,floor()返回整数(并且对于前面提到的特殊情况返回溢出错误)。

那么现在 int()floor()之间有什么区别呢?

54512 次浏览

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 the time complexity of both methods, they are the same.

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

I wrote this method, does the trick for me,

def rightInteger(numa, numb):
result = numa/numb
next_int = math.ceil(result)
difference = next_int -result
if(difference <=0.5):
return next_int
else:
return math.floor(result)