简体   繁体   English

在Python中更快地将float转换为int

[英]Faster float to int conversion in Python

Here's a piece of code that takes most time in my program, according to timeit statistics. 根据timeit统计,这是一段代码,该代码在我的程序中耗时最多。 It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. 将[-1.0,1.0]间隔中的浮点数转换为无符号整数[0,2 ** 32]是一个肮脏的函数。 How can I accelerate floatToInt ? 如何加速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

Did you try the obvious one? 您尝试过显而易见的吗?

def floatToInt(x):
    return int((x+1.0) * (2**31))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM