Suppose you want to compute the square root of x (x > 0) using the following met
ID: 3775482 • Letter: S
Question
Suppose you want to compute the square root of x (x > 0) using the following method:
- guess a number g (for example guess = 7) for the square root of x,
- a better new guess is (g + x/g)/2 until |x – (g^2)| is less than or equal to a given epsilon
Write a recursive helper method
public static squareRootGuess(double x, double g). If (g^2) is approximately equal to x (i.e. |x – (g^2)| < 0.0001), return g, otherwise, return squareRootGuess with the better new guess ((g + x/g)/2). Then write a method public static squareRoot(double x) that uses the helper method.
Example:
Calculate the square root of x = 10; initial guess = 7
squareRootGuess(10, 7) -> |10 – (7^2)| > 0.0001;
return new guess = (7 + 10/7)/2 = 4.21428
squareRootGuess(10, 4.21428) -> |10 – ((4.21428)^2)| > 0.0001;
return new guess = (4.21428 + 10/4.21428)/2 = 3.29358
squareRootGuess(10, 3.29358) -> . . .
. . .
. . .
Java program. Please, the program can compile and run. Thanks!!
Explanation / Answer
public class RecursiveSquareRoot {
static final double epsilon =0.0001;
public static void main(String[] args) {
System.out.println(squareRoot(10));
}
public static double squareRootGuess(double x, double g){
if(Math.abs(x-(g*g)) > epsilon)
return squareRootGuess(x,((g + x/g)/2));
else
return g;
}
public static double squareRoot(double x)
{
return squareRootGuess(x,x);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.