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
    }
}

How have you determined that it is "being ignored"? Put a print statement in there to see. Also, you do know that after the first iteration both x0 and xn have the same value, meaning that in the second iteration 0 is not greater than .0001 and the loop exits, right? I assume that you should be refiguring the xn value after assigning xn to x0, no?

Does the new x0 not affect the expression that makes up xn after the first iteration?

No. You have to do the math again. The variables are simple primitives not Closures.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.