Search code examples
pythonperformancefloating-pointcoding-style

Should I use float literals to represent integer numbers as floats in Python?


Consider a function that is to return a half of a float argument. Should it better be the first or the second?

def half_a(x: float) -> float:
    return x / 2

def half_b(x: float) -> float:
    return x / 2.0

Is there any performance difference or is there a style convention that would say one of these is better than the other?

Clearly half_a looks better and a more complex piece of code may get more readable written this way but in some other languages it is either necessary or preferable to use the half_b version to avoid run-time type conversion.


Solution

  • float divided by float is slightly faster than float divided by int:

    >>> timeit.timeit('n/2', 'n=123456.789') 
    0.04134701284306175
    >>> timeit.timeit('n/2.0', 'n=123456.789')
    0.03455621766488548
    >>> timeit.timeit('[n/2 for n in r]', 'r = [n*5/1.1 for n in range(1, 10001)]', number=10000)
    5.177127423787169
    >>> timeit.timeit('[n/2.0 for n in r]', 'r = [n*5/1.1 for n in range(1, 10001)]', number=10000)
    4.067747102254316