Implement a recursive algorithm to find the square root of a given number The fo
ID: 3628822 • Letter: I
Question
Implement a recursive algorithm to find the square root of a given numberThe following algorithm finds the square root of a positive number:
Algorithm squareRoot(number, lowGuess, highGuess, tolerance)
newGuess=(lowGuess + highGuess) / 2
if ((highGuess – newGuess) / newGuess < tolerance)
return newGuess
else if (newGuess * newGuess > number)
return squareRoot (number, lowGuess, newGuess, tolerance)
else if (newGuess * newGuess < number)
return squareRoot (number, newGuess, highGuess , tolerance)
else
return newGuess
To begin the computation, you will need a value lowGuess that is less than the square root of the number and a value highGuess that is larger. You can use zero as lowGuess and the number itself as highGuess. The parameter tolerance controls the precision of the result independently of the magnitude of number. For example, computing the square root of 250 with tolerance equal to 0.0005 results in 15.81. This result has four digits of accuracy.
Explanation / Answer
please rate - thanks
import java.util.*;
public class recursiveSquareRoot
{public static void main(String args[])
{double number,lowGuess=0,highGuess,tolerance=.0005;
Scanner in =new Scanner(System.in);
System.out.print("Enter a number whose square root you want: ");
number=in.nextDouble();
highGuess=number;
System.out.println("sqrt("+number+")="+squareRoot(number, lowGuess, highGuess, tolerance));
}
public static double squareRoot(double number,double lowGuess,double highGuess,double tolerance)
{double newGuess=(lowGuess + highGuess) / 2;
if ((highGuess-newGuess) / newGuess < tolerance)
return newGuess;
else if (newGuess * newGuess > number)
return squareRoot (number, lowGuess, newGuess, tolerance);
else if (newGuess * newGuess < number)
return squareRoot (number, newGuess, highGuess , tolerance);
else
return newGuess;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.