sqrt(1.0 - pow(1.0,2)) returns -nan
<p>I've found an interesting floating point problem. I have to calculate several square roots in my code, and the expression is like this:</p>

<pre><code>sqrt(1.0 - pow(pos,2))
</code></pre>

<p>where pos goes from -1.0 to 1.0 in a loop. The -1.0 is fine for pow, but when pos=1.0, I get an -nan. Doing some tests, using gcc 4.4.5 and icc 12.0, the output of </p>

<pre><code>1.0 - pow(pos,2) = -1.33226763e-15
</code></pre>

<p>and </p>

<pre><code>1.0 - pow(1.0,2) = 0
</code></pre>

<p>or</p>

<pre><code>poss = 1.0
1.0 - pow(poss,2) = 0
</code></pre>

<p>Where clearly the first one is going to give problems, being negative. Anyone knows why pow is returning a number smaller than 0? The full offending code is below:</p>

<pre><code>int main() {
  double n_max = 10;
  double a = -1.0;
  double b = 1.0;
  int divisions = int(5 * n_max);
  assert (!(b == a));

  double interval = b - a;
  double delta_theta = interval / divisions;
  double delta_thetaover2 = delta_theta / 2.0;
  double pos = a;
  //for (int i = 0; i &lt; divisions - 1; i++) {
   for (int i = 0; i &lt; divisions+1; i++) {

    cout&lt;&lt;sqrt(1.0 - pow(pos, 2)) &lt;&lt;setw(20)&lt;&lt;pos&lt;&lt;endl;

     if(isnan(sqrt(1.0 - pow(pos, 2)))){
      cout&lt;&lt;"Danger Will Robinson!"&lt;&lt;endl;
      cout&lt;&lt; sqrt(1.0 - pow(pos,2))&lt;&lt;endl;
      cout&lt;&lt;"pos "&lt;&lt;setprecision(9)&lt;&lt;pos&lt;&lt;endl;
      cout&lt;&lt;"pow(pos,2) "&lt;&lt;setprecision(9)&lt;&lt;pow(pos, 2)&lt;&lt;endl;
      cout&lt;&lt;"delta_theta "&lt;&lt;delta_theta&lt;&lt;endl;
      cout&lt;&lt;"1 - pow "&lt;&lt; 1.0 - pow(pos,2)&lt;&lt;endl;
      double poss = 1.0;
      cout&lt;&lt;"1- poss "&lt;&lt;1.0 - pow(poss,2)&lt;&lt;endl;


  }

  pos += delta_theta;

}

 return 0;
 }
</code></pre>
