1

I know that log2(x) accuracy fails when x is large enough and is in the form 2^n-1 for most languages, except R and Matlab may be. Any specific reasons ?

Edit 1: x is an integer around 10^15 and up

vozille
  • 115
  • 1
  • 9

2 Answers2

2

When x is large enough (about 4.5E15 for an IEEE double, I think), 2^n-1 isn't representable.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

This is a general floating point (IEEE 754) imprecision issue and has little to do with the log function. At some point a difference of one can no longer be represented in the floating point number, because setting the next bit in the mantissa would add an amount possibly much larger than one to the number. Consider this example:

int main() {
    double d = 4.5E15;
    while(d != d + 1){++d;} //should always be true: d != d + 1
    cout << d;
    return 0;
}

You might expect this to run infinitely, but instead this returns immediately and prints 4.5E15 on my platform and very likely on yours too.

midor
  • 5,487
  • 2
  • 23
  • 52
  • 1
    `while(d != ++d){}` - there's no sequence point there - it's undefined behaviour... perhaps `while (d != d + 1) ++d;` would make your point? – Tony Delroy Feb 20 '15 at 09:46