Python 3 中的 int() 和 floor() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31036098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between int() and floor() in Python 3?
提问by datah4ck3r
In Python 2, floor()
returned a float value. Although not obvious to me, I found a few explanations clarifying why it may be useful to have floor()
return float (for cases like float('inf')
and float('nan')
).
在 Python 2 中,floor()
返回一个浮点值。虽然对我来说并不明显,但我发现了一些解释,阐明了为什么floor()
返回浮动可能有用(对于float('inf')
和 之类的情况float('nan')
)。
However, in Python 3, floor()
returns integer (and returns overflow error for the special cases mentioned before).
但是,在 Python 3 中,floor()
返回整数(并为前面提到的特殊情况返回溢出错误)。
So what is the difference, if any, between int()
and floor()
now?
那么int()
,floor()
现在和现在有什么区别,如果有的话?
采纳答案by Martijn Pieters
floor()
rounds down. int()
truncates. The difference is clear when you use negative numbers:
floor()
几轮下来。int()
截断. 当您使用负数时,区别很明显:
>>> 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.
负数四舍五入意味着它们远离 0,截断使它们更接近 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.
换句话说,floor()
总是会低于或等于原始值。int()
将接近于零或相等。
回答by amin saffar
I test time complexity of both method they are the same
我测试了两种方法的时间复杂度它们是相同的
from time import time
import math
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