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

Implement a class RootApproximator that starts with an initial guess of 1 and wh

ID: 3625540 • Letter: I

Question


Implement a class RootApproximator that starts with an initial guess of 1 and whose nextGuess method produces a sequence of increasingly better guesses. Supply a method hasMoreGuesses that returns false if two successive guesses are sufficiently close to each other (that is, they differ by no more than a small value ). Then test your class like this:
RootApproximator approx = new RootApproximator(a, EPSILON);
while (approx.hasMoreGuesses())
System.out.println(approx.nextGuess());

Here is a sample program run:

Enter a number that you want a square root of: 4
1.0
2.5
2.05
2.000609756097561
2.0000000929222947
2.000000000000002
2.0
Use the following class as your main class:

import java.util.Scanner;

/**
This program calculates a square root without calling Math.sqrt.
*/
public class RootCalculator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number that you want a square root of: ");
double a = in.nextDouble();
final double EPSILON = 1E-12;

RootApproximator r = new RootApproximator(a, EPSILON);

while (r.hasMoreGuesses())
System.out.println(r.nextGuess());
}
}
You need to supply the following class in your solution:

RootApproximator
Use the following class as your tester class:

public class RootApproximatorTester
{
public static void main(String[] args)
{
double a = 100;
final double EPSILON = 1;
RootApproximator approx = new RootApproximator(a, EPSILON);
System.out.println(approx.nextGuess());
System.out.println("Expected: 1");
System.out.println(approx.nextGuess());
System.out.println("Expected: 50.5");
while (approx.hasMoreGuesses())
approx.nextGuess();
System.out.println(Math.abs(approx.nextGuess() - 10) < EPSILON);
System.out.println("Expected: true");
}
}

Explanation / Answer

public class RootApproximator {
    double lastGuess = -1;
    double guess = 1.0;
    double epsilon;
    double a; // number whose square root we're approximating
    public RootApproximator(double a, double epsilon) {
        this.epsilon = epsilon;
        this.a = a;
    }

    public double nextGuess() {
        lastGuess = guess;
        guess = 0.5*(guess+a/guess);
        return lastGuess;
    }

    public boolean hasMoreGuesses() {
        return lastGuess==-1 || (Math.abs(guess-lastGuess) > epsilon);
    }
   
}

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