Faster float to int conversion in Python
Posted
by culebrón
on Stack Overflow
See other posts from Stack Overflow
or by culebrón
Published on 2010-03-23T12:49:39Z
Indexed on
2010/03/23
12:53 UTC
Read the original article
Hit count: 317
Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt
?
piece = []
rng = range(32)
for i in rng:
piece.append(1.0/2**i)
def floatToInt(x):
n = x + 1.0
res = 0
for i in rng:
if n >= piece[i]:
res += 2**(31-i)
n -= piece[i]
return res
© Stack Overflow or respective owner