Why is my while statement being ignored?
Problem:
Write a method called squareRoot that takes a double as a parameter and that returns
an approximation of the square root of the parameter, using this algorithm. You may
not use the built-in method Math.sqrt.
As your initial guess, you should use a/2. Your method should iterate until it gets two consecutive estimates that differ by less than 0.0001; in other words, until the absolute value of xn − xn−1 is less than 0.0001. You can use the built-in method Math.abs to calculate the absolute value.
package squareroot;
/**
*
* @author Josh
*/
public class Main {
public static void main (String[] args) {
squareRoot (10.0);
// invokes squareRoot
}
public static void squareRoot (double n) {
double x0 = n / 2;
double xn = (x0 + n / x0) / 2;
// square root approximation of n
while ( Math.abs (x0 - xn) > (.0001) ) {
// while the absolute values of approximations have
// a difference greater than .0001, run the method
x0 = xn;
}
System.out.println ("The square root of " + n + " is " + xn);
// else, print the square root of n
}
}