Ivan
Ivan

Reputation: 64227

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.

Upvotes: 0

Views: 2883

Answers (2)

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

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

Upvotes: 1

blue note
blue note

Reputation: 29099

It's hard to know if there's a performance difference (and if there is, it's definitely negligible). Regarding style, there is also no common convention. However, I would choose the first one, if you are on python 3+. Python 3 has a different operator for integer division. See below

x = 2
print(type(x)) # int
print(type(x / 2)) # float
print(type(x // 2)) # int

On the other hand, if you are on python 2, you should probably choose the second one, because if your argument happens to be an int

print(2/5) # 0

Upvotes: 2

Related Questions