[music-dsp] JUCE rounding hack

robert bristow-johnson rbj at audioimagination.com
Wed Sep 11 23:50:23 EDT 2013



can anyone tell me how this hack works?  i can hardly believe that it does.

i am reasonably well familiar with the IEEE-754 format for either floats 
or doubles.  how does this get past the exponent?

FYI: log2(6755399441055744.0) = 52.5849625007212

but

      log2(2/3*6755399441055744.0) = 52.000000000000

so i s'pose that has something to do with it.

so 4503599627370496 = 2^52   adds the "hidden 1 bit"

and  2251799813685248 = 2^51  adds half of that to round to nearest??

how does it know where the implied binary point is?

just doesn't make much sense to me.

-- 

r b-j                  rbj at audioimagination.com

"Imagination is more important than knowledge."






//==============================================================================
/** Fast floating-point-to-integer conversion.

     This is faster than using the normal c++ cast to convert a float to 
an int, and
     it will round the value to the nearest integer, rather than 
rounding it down
     like the normal cast does.

     Note that this routine gets its speed at the expense of some 
accuracy, and when
     rounding values whose floating point component is exactly 0.5, odd 
numbers and
     even numbers will be rounded up or down differently.
*/
template <typename FloatType>
inline int roundToInt (const FloatType value) noexcept
{
     union { int asInt[2]; double asDouble; } n;
     n.asDouble = ((double) value) + 6755399441055744.0;

     #if JUCE_BIG_ENDIAN
       return n.asInt [1];
     #else
       return n.asInt [0];
     #endif
}

/** Fast floating-point-to-integer conversion.

     This is a slightly slower and slightly more accurate version of 
roundDoubleToInt(). It works
     fine for values above zero, but negative numbers are rounded the 
wrong way.
*/
inline int roundToIntAccurate (const double value) noexcept
{
     return roundToInt (value + 1.5e-8);
}






More information about the music-dsp mailing list