Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Assistance A common way of calculating the square root is by successive app

ID: 3564866 • Letter: J

Question

Java Assistance

A common way of calculating the square root is by successive approximations. To calculate sqrt(x):

For example, to calculate sqrt(2) (assuming we care only about the first 5 decimal places):

1?2 (1 + 2?1) = 1.5

1?2 (1.5 + 2?1.5) = 1.41667

1?2 (1.41667 + 2?1.41667) = 1.41422

Create a class SquareRoot with the following methods:

Approximates the square root of x by improving the guess (recursively).
At each stage of the approximation, sqrtIter should print out the current guess.

which finds the square root of x by calling sqrtIter using an initial guess of 1

SquareRoot should also have a main method that asks the user for a number, and then prints the result of sqrt using that number.

Since you will be comparing doubles, you should use a TOLERANCE of 0.00001

Example Dialog:

Explanation / Answer

===============================

Program for SquareRoot.java

===============================

import java.math.BigDecimal;
import java.util.Scanner;

public class SquareRoot {

   public static void main(String[] args) {
  

       Double n;
       Scanner sc = new Scanner(System.in);
       System.out.print("Enter a number:");
       n=sc.nextDouble();
      

       System.out.println("sqrt("+n+"):"+sqrt(n));
   }
  

   public static double sqrt(double x) {
      

       double sqrt;
       sqrt = sqrtIter(1,x);
       return sqrt;
   }

   public static double sqrtIter(double guess, double x) {
      
      
System.out.println(guess);
       Double TOLERANCE= 0.00001;
      
       BigDecimal bd ;
      
       do {
           guess=(0.5)*(guess+x/guess);
          
           bd = new BigDecimal(Double.toString(guess*guess));
           bd = bd.setScale(5,BigDecimal.ROUND_HALF_UP);
          
           if((x+TOLERANCE==bd.doubleValue())||
                   (x==bd.doubleValue())){
               break;
           }
           System.out.println(guess);

       } while(guess*guess>=x);
      
       return guess;
      
   }
}

==========================================

Output

==========================================

Case1:

Enter a number:2
1.0
1.5
1.4166666666666665
sqrt(2.0):1.4142156862745097

Case2:

Enter a number:5
1.0
3.0
2.3333333333333335
2.238095238095238
sqrt(5.0):2.2360688956433634

case3:

Enter a number:9
1.0
5.0
3.4
3.023529411764706
3.00009155413138
sqrt(9.0):3.000000001396984

==============================================

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote