How to detect if a base 10 decimal can be represented exactly in base 2
<p>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?</p>

<p>My first guess is as follows:</p>

<pre><code>bool canBeRepresentedInBase2(const double &amp;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 &lt; nbOfDoublings ; i++)
    {
     doubledNumber = 2*doubledNumber;
     double intPart;
     double fracPart = modf(doubledNumber/2, &amp;intPart);
     if (fracPart == 0) //number can be represented exactly in base 2
     {
      funcResult = true;
      break;
     }
    }
    return funcResult;
}
</code></pre>

<p>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.</p>

<p>Any better ideas?</p>
