【问题标题】:What is the difference between int() and floor() in Python 3?Python 3 中的 int() 和 floor() 有什么区别?
【发布时间】:2015-06-24 20:13:58
【问题描述】:
在 Python 2 中,floor() 返回一个浮点值。虽然对我来说不是很明显,但我找到了一些解释,说明了为什么让 floor() 返回浮点数可能有用(对于像 float('inf') 和 float('nan') 这样的情况)。
但是,在 Python 3 中,floor() 返回整数(并且对于前面提到的特殊情况返回溢出错误)。
那么现在int() 和floor() 之间有什么区别(如果有的话)?
【问题讨论】:
标签:
python
python-3.x
floating-point
【解决方案1】:
floor() 循环向下。 int() 截断。使用负数时区别很明显:
>>> import math
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3
对负数进行四舍五入意味着它们远离 0,截断使它们更接近 0。
换句话说,floor() 总是会低于或等于原始值。 int() 将接近于零或等于。
【解决方案2】:
我测试了这两种方法的时间复杂度,它们是一样的。
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))
输出是:
# function floor takes 11.841985
# function int takes 11.841325