As part of a numerical library test I need to choose base 10 decimal numbers that can be represented exactly in base 2. How do you detect in C++ if a base 10 decimal number can be represented exactly in base 2?
My first guess is as follows:
bool canBeRepresentedInBase2(const double &pNumberInBase10) { //check if a number in base 10 can be represented exactly in base 2 //reference: http://en.wikipedia.org/wiki/Binary_numeral_system bool funcResult = false; int nbOfDoublings = 16*3; double doubledNumber = pNumberInBase10; for (int i = 0; i < nbOfDoublings ; i++) { doubledNumber = 2*doubledNumber; double intPart; double fracPart = modf(doubledNumber/2, &intPart); if (fracPart == 0) //number can be represented exactly in base 2 { funcResult = true; break; } } return funcResult; }
I tested this function with the following values: -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. It returns true for -1.0/4.0, 0.0, 7.0/8.0, 1.0, 99.005 which is correct.
Any better ideas?
I think what you are looking for is a number which has a fractional portion which is the sum of a sequence of negative powers of 2 (aka: 1 over a power of 2). I believe this should always be able to be represented exactly in IEEE floats/doubles.
For example:
0.375 = (1/4 + 1/8) which should have an exact representation.
If you want to generate these. You could try do something like this:
EDIT: I believe your function has a broken interface. It would be better if you had this:
because not all fractions have exact representations, but the moment you shove it into a double, you’ve chosen a representation in binary… defeating the purpose of the test.