JAVA Language PLEASE:
Programming Fundamentals III – Java Data Structures
Problem: Complete Programming Project 1, page 290.
The 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 need a value lowGuess 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.00005 results in 15.81. This result has four digits of accuracy.
Implement this algorithm.
Submission:This lab needs only one .java file,
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! Note: Name the java file as SquareRoot.java and copy paste the code in the file. =========================================================================== import java.util.Scanner;
public class SquareRoot { 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 { return squareRoot(number, newGuess, highGuess, tolerance); } } public static void main(String[] args) { final double TOLERANCE = 0.00005; Scanner scanner = new Scanner(System.in); System.out.print("Enter a number whose square root you like to compute: "); double num = scanner.nextDouble(); if (num < 0) num = -num; System.out.printf("Square Root: %.2f\n", squareRoot(num, 0, num, TOLERANCE)); } } =======================================================================
Get Answers For Free
Most questions answered within 1 hours.