我需要一位浮点专家
谁能向我详细解释一下这个 log2 函数是如何工作的:
inline float fast_log2 (float val)
{
int * const exp_ptr = reinterpret_cast <int *> (&val);
int x = *exp_ptr;
const int log_2 = ((x >> 23) & 255) - 128;
x &= ~(255 << 23);
x += 127 << 23;
*exp_ptr = x;
val = ((-1.0f/3) * val + 2) * val - 2.0f/3; // (1)
return (val + log_2);
}
Can anyone explain to me in detail how this log2 function works:
inline float fast_log2 (float val)
{
int * const exp_ptr = reinterpret_cast <int *> (&val);
int x = *exp_ptr;
const int log_2 = ((x >> 23) & 255) - 128;
x &= ~(255 << 23);
x += 127 << 23;
*exp_ptr = x;
val = ((-1.0f/3) * val + 2) * val - 2.0f/3; // (1)
return (val + log_2);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IEEE 浮点数内部有一个指数
E
和一个尾数M
,每个都表示为二进制整数。实际值基本上是基本对数数学表示:
代码的第一部分将
E
和 M 分开。注释行 (1) 使用多项式计算log2(M)
近似。最后一行添加E
和近似结果。IEEE floats internally have an exponent
E
and a mantissaM
, each represented as binary integers. The actual value is basicallyBasic logarithmic math says:
The first part of your code separates
E
and M. The line commented (1) computeslog2(M)
by using a polynomial approximation. The final line addsE
and the result of the approximation.这是一个近似值。它首先直接获取指数的 log2(这很简单),然后使用尾数的 log2 的近似公式。然后将这两个 log2 分量相加得到最终结果。
It's an approximation. It first takes log2 of the exponent directly (trivial to do), then uses an approximation formula for log2 of the mantissa. It then adds these two log2 components to give the final result.