Skip to main content
 首页 » 编程设计

python之我们可以说 math.floor(x) == int(x) 是相似的吗

2025年05月04日11yyy_WW

<分区>

当我想将 float 转换为整数值时,我可以选择 math.floor 或将其转换为 int,这两个结果是相同的。

性能::int 似乎快了 30%

def floorTest(): 
    [math.floor(float(i)) for i in range(10)] 
def intTest(): 
    [int(float(i)) for i in range(10)] 
 
import timeit 
print(timeit.timeit(stmt='floorTest()', setup='from __main__ import floorTest', number=10**7)) 
print(timeit.timeit(stmt='intTest()', setup='from __main__ import intTest', number=10**7)) 

反汇编程序:我不打算粘贴结果,因为它们对于上述性能中的 floorTest 和 intTest 是相同的测试。

现在是问题:

Can we say math.floor() has the same effect as casting a float to int?

我问的原因是,我可能会监督一些要点。