title: Recursive Newton Square Root Function Only Terminates for Perfect Squares
body: <p>I wrote a program that looks very similar to other recursive newton square root functions I have seen on the web. For some reason this one only works with perfect squares and I can't seem to find a reason why. I have tried passing 3 variables(epsilon), setting x=a, setting a = to the equation passed in line 9 then passing abs(a*a-x). I tried to describe it the best I could it's a slightly new topic for me and I am just not sure if this is only capable of finding perfect roots or if my code/equation is incorrect. </p>
  
  <pre><code> 1  #include &lt;cmath&gt;
   2  #include &lt;iostream&gt;
   3  using namespace std;
   4
   5  double newtroot(double x, double a) {
   6      if (fabs(a*a - x) &lt;= DBL_EPSILON)
   7          return a;
   8      else 
   9          return newtroot(x, fabs(a*a + x)/(2*a));
  10  }
  11
  12  int main() {
  13      cout &lt;&lt; newtroot(9, 1) &lt;&lt; endl;
  14      system("pause");
  15      return 0;
  16  }
  </code></pre>
  
  <p>EDIT: The function does not only work for perfect squares but it only returns correctly for perfect squares. If it is not a perfect square <code>a</code> ends up being the correct value (checked in the debugger) but the recursion never stops. I figured it must be something with the comparison in line 6 so I tried replacing DBL_EPSILON with <code>a</code> and the incorrect value is returned.<br>
  This error also shows on line 6 when a non-perfect square is entered: </p>
  
  <blockquote>
    <p>Unhandled exception at 0x00007FFE8E9C06F0 (ucrtbased.dll) in RecursionProgrammingExcercisesMurphyT.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000013B2603FE8). occurred</p>
  </blockquote>