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

Questtion3: Modify Sqrt.java so that it reports an error if the user enters a ne

ID: 3638033 • Letter: Q

Question

Questtion3: Modify Sqrt.java so that it reports an error if the user enters a negative number
and works properly if the user enters zero.
public class Sqrt {
public static void main(String[] args) {
// read in the command-line argument
double c = Double.parseDouble(args[0]);
double epsilon = 1e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision
is achieved
while (Math.abs(t - c/t) > epsilon*t) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
}

Explanation / Answer

public class Sqrt { public static void main(String[] args) { // read in the command-line argument double c = Double.parseDouble(args[0]); if (c < 0) { System.out.println("Error: number cannot be negative"); } else if (c == 0) { System.out.println(0); } else { double epsilon = 1e-15; // relative error tolerance double t = c; // estimate of the square root of c // repeatedly apply Newton update step until desired precision is achieved while (Math.abs(t - c/t) > epsilon*t) { t = (c/t + t) / 2.0; } // print out the estimate of the square root of c System.out.println(t); } } }