write a java method named sqrt() that will calculate the square root of a positi
ID: 3546781 • Letter: W
Question
write a java method named sqrt() that will calculate the square root of a positive double to within a specified level of tolerance. The signature of the method should be:
public static double sqrt(double number, double tolerance)
The basic solution logic, is that sqrt() will call a private recursive method that has two additional parameters, lowGuess and highGuess, it will have the signature:
private static double sqrt( double number, double lowGuess, double highGuess, double tolerance)
Each time the private method is called, it will calculate a newGuess that is the mid-point between the lowGuess and the highGuess, There are three possible cases:
1) The base case is satisfied when:
(highGuess - newGuess) / newGuess < tolerance, and newGuess is returned
2) otherwise, if newGuess*newGuess < number, make a recursive call substituting newGuess for lowGuess.
3) Or, if newGuess * newGuess < number, make a recursive call substituting newGuess for lowGuess.
The public sqrt method will provide 0 and number as the original lowGuess and highGuess values to the private recursive version, and it will return the result eventually returned by its private helper.
Write a public java class named Lab4A to contain the two overloaded sqrt methods, and a main() method that will, Using console I/O, promp the user in a continuous loop to enter a positive number and a tolerance, and display the final square root found from the methods above. The input loop should be exited if the number entered is zero or negative.
Explanation / Answer
please rate - thanks
any question - ask
import java.util.*;
public class Lab4A
{public static void main(String args[])
{double number,tolerance;
Scanner in =new Scanner(System.in);
System.out.print("Enter a number whose square root you want(<=0 to exit): ");
number=in.nextDouble();
while(number>=0)
{System.out.print("Enter tolerance: ");
tolerance=in.nextDouble();
System.out.println("sqrt("+number+")="+sqrt(number, tolerance));
System.out.print("Enter a number whose square root you want(<=0 to exit): ");
number=in.nextDouble();
}
}
public static double sqrt(double number, double tolerance)
{return sqrt(number, 0, number, tolerance);
}
public static double sqrt(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 sqrt (number, lowGuess, newGuess, tolerance);
else if (newGuess * newGuess < number)
return sqrt (number, newGuess, highGuess , tolerance);
else
return newGuess;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.