快速 log2(float x) 实现 C++ [英] Fast log2(float x) implementation C++
问题描述
我需要在 C++ 中非常快速地实现 log2(float x) 函数.
I need a Very-Fast implementation of log2(float x) function in C++.
我发现了一个非常有趣的实现(而且速度非常快!)
I found a very interesting implementation (and extremely fast!)
#include <intrin.h>
inline unsigned long log2(int x)
{
unsigned long y;
_BitScanReverse(&y, x);
return y;
}
但是这个函数只适用于输入中的整数值.
But this function is good only for integer values in input.
问题:有没有办法把这个函数转换成double类型的输入变量?
Question: Is there any way to convert this function to double type input variable?
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;
}
这比前面的例子快得多,但输出是无符号类型.
which is much faster than the previous example, but the output is unsigned type.
是否可以让这个函数返回一个double类型?
Is it possible to make this function return a double type?
提前致谢!
推荐答案
如果你只需要对数的整数部分,那么你可以直接从浮点数中提取出来.
If you just need the integer part of the logarithm, then you can extract that directly from the floating point number.
便携:
#include <cmath>
int log2_fast(double d) {
int result;
std::frexp(d, &result);
return result-1;
}
可能更快,但依赖于未指定和未定义的行为:
Possibly faster, but relying on unspecified and undefined behaviour:
int log2_evil(double d) {
return ((reinterpret_cast<unsigned long long&>(d) >> 52) & 0x7ff) - 1023;
}
这篇关于快速 log2(float x) 实现 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!