c++ - How to detect if a base 10 decimal can be represented exactly in base 2 -


As part of a numerical library test, I need to select the base 10 decimals which are exactly displayed in base 2 can go. Can you find in C ++ if the base 10 decimal number can be represented exactly in base 2?

My first estimate is as follows:

  bool canBeRepresentedInBase2 (const double & amp; pNumberInBase10) {// Check that a number in base 10 is exactly the base 2 / reference Can be displayed: http://en.wikipedia.org/wiki/Binary_numeral_system bool funcResult = false; Int nbOfDoublings = 16 * 3; Double double number = PNambar Inbase 10; (For int i = 0; i & lt; nbOfDoublings; i ++) (doubledNumber = 2 * doubledNumber; double interpart; double fracPart = modf (double number / 2, & intpart); if (fracPart == 0 ) // number can be represented in exactly 2 bases {funcResult = true; breakdown;}} genetic result to return;}  

I tested this function with the following values It is -1.0 / 4.0, 0.0, 0.1, 0.2, 0.205, 1.0 / 3.0, 7.0 / 8.0, 1.0, 256.0 / 255.0, 1.02, 99.005. This is true -1.0 / 4.0, 0.0, 7.0 / 8.0, 1.0, 99.005 Right?

Any better ideas?

Comments