1

When I want to convert a float to an integer value I have the options math.floor or casting it to int, both results are the same.

Performance:: int seems to be 30% faster

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))

Disassembler: I'm not going to paste the outcome, as they are the same for both floorTest and intTest from the aforementioned Performance test.

Now the Question:

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

The reason I'm asking is, that i might be overseeing some points.

codeczar
  • 273
  • 1
  • 8
  • 22
user1767754
  • 23,311
  • 18
  • 141
  • 164

1 Answers1

9

No, int and math.floor have different behaviour:

>>> import math
>>> f = 1.23456
>>> int(f)
1
>>> int(-f)
-1
>>> math.floor(f)
1
>>> math.floor(-f)
-2