0

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
    }
}
2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by masijade
0

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?

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.