Suppose you want to compute the square root of x (x > 0) using the following met
ID: 3775006 • 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 g2 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
import java.util.Scanner;
/** method to approximate the square root of a given number.
*/
public class CalculateSquareRoot
{
public static void main(String[] args)
{
//prompt the user for n
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
double x = in.nextDouble();
System.out.println(" The square root is " + squareRoot(x));
}
//function which calls guess square root method
public static double squareRoot(double x)
{
return squareRootGuess(x, 5);
}
//function which calculates approx square root value
private static double squareRootGuess(double x, double g)
{
//initialize approx diff value
final double epsilon = .0001;
//if difference < diff value
if (Math.abs(x - g * g) < epsilon)
{
return g;
}
//otherwise recursively cal square root
else
{
return squareRootGuess(x, 0.5 * (g + x / g));
}
}
}
Sample Output:
Enter a number: 16
The square root is 4.0000001858445895
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.