Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

/** * Determines the number of iterations of Newton\'s method * required to appr

ID: 3726671 • Letter: #

Question

/**
* Determines the number of iterations of Newton's method
* required to approximate the square root of x within
* the given bound. Newton's method starts out by
* setting the initial approximate <em>answer</em> to x.  
* Then in each iteration, <em>answer</em> is replaced by
* the quantity <em>(answer + x / answer) / 2.0</em>.
* The process stops when the difference between
* x and <em>(answer * answer)</em> is strictly less than
* the given bound <code>err</code>. The method
* returns the number of iterations required.
* The given value x must be non-negative.
* <p>
* For example, given x = 10 the first three iterations
* of Newton's method produce the approximate values
* 5.5, 3.66, and 3.20. Those three values squared are
* 30.29, 13.39, and 10.21, respectively.
* Therefore <code>countIterations(10, 1.0)</code>
* returns 3, since it takes 3 iterations to get the result 10.21
* that is within 1.0 of x.  
* On the other hand, <code>countIterations(10, 200)</code> returns 0,
* since 10 * 10 = 100 is already within 200 units of x = 10.
* @param x
* value whose square root is to be approximated
* @param err
* given bound for the approximation
* @return
* number of iterations required to get an approximation
* whose square is within the given bound of x
*/
public static int countIterations(double x, double err)
{
// TODO
return 0;
}

Explanation / Answer

public static int countIterations(double x, double err)
{
    // TODO
   double answer = x;
   if(x+err>=answer*answer&&x-err<=answer*answer)
       return 0;
   int iterations = 0;
   while(!(x+err>=answer*answer&&x-err<=answer*answer))
   {
       answer = (answer+x/answer)/2.0;
       iterations++;
   }
   return iterations;
}