我需要一位浮点专家

发布于 2024-10-07 18:51:06 字数 421 浏览 0 评论 0原文

谁能向我详细解释一下这个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-10-14 18:51:06

IEEE 浮点数内部有一个指数 E 和一个尾数 M,每个都表示为二进制整数。实际值基本上是

2^E * M

基本对数数学表示:

  log2(2^E * M) 
= log2(2^E) + log2(M)
= E + log2(M)

代码的第一部分将 E 和 M 分开。注释行 (1) 使用多项式计算 log2(M)近似。最后一行添加 E 和近似结果。

IEEE floats internally have an exponent E and a mantissa M, each represented as binary integers. The actual value is basically

2^E * M

Basic logarithmic math says:

  log2(2^E * M) 
= log2(2^E) + log2(M)
= E + log2(M)

The first part of your code separates E and M. The line commented (1) computes log2(M) by using a polynomial approximation. The final line adds E and the result of the approximation.

我乃一代侩神 2024-10-14 18:51:06

这是一个近似值。它首先直接获取指数的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文