Question

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);
} 
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top