小编Pom*_*ron的帖子

快速log2(float x)实现C++

我需要在C++中实现非常快速的log2(float x)函数.

我发现了一个非常有趣的实现(非常快!)

#include <intrin.h>

inline unsigned long log2(int x)
{
    unsigned long y;
    _BitScanReverse(&y, x);
    return y;
}
Run Code Online (Sandbox Code Playgroud)

但是此函数仅适用于输入中的整数值.

问题:有没有办法将此函数转换为double类型的输入变量?

UPD:

我找到了这个实现:

typedef unsigned long uint32;
typedef long int32;   
static inline int32 ilog2(float x)
{
    uint32 ix = (uint32&)x;
    uint32 exp = (ix >> 23) & 0xFF;
    int32 log2 = int32(exp) - 127;

    return log2;
}
Run Code Online (Sandbox Code Playgroud)

这比前一个示例快得多,但输出是无符号类型.

是否可以使此函数返回double类型?

提前致谢!

c++ performance

7
推荐指数
4
解决办法
1万
查看次数

标签 统计

c++ ×1

performance ×1