Search code examples
mathfloating-pointieee-754logarithm

I'm in need for a floating point expert


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);
} 

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.