Question

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
Was it helpful?

Solution

Did you try the obvious one?

def floatToInt(x):
    return int((x+1.0) * (2**31))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top