<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import CS99.*;

/**
 * SquareRoot - Lab 6
 * Author: Michael Clarkson
 * NetID: mrc26
 * Date: 7/10/00
 */
class SquareRoot { 

	public static void main(String[] args) {
		
		double number;			// the number to take the root of
		double firstGuess;		// first approx to the root of number
		double desiredAccuracy;	// error tolerance for root
		double approxRoot;		// approximate square root according to Newton-Raphson's method
		double actualRoot;		// actual square root of number according to Math.sqrt()
		
		System.out.println("Square Root Approximator");
		System.out.println();
		
		do {
			System.out.print("Enter the number to take the square root of: ");
			number = Console.readDouble();
			if (number &lt; 0.0) {
				System.out.println("Number must be positive.");
			}
		} while (number &lt; 0.0);
		
		System.out.print("Enter the first approximation: ");
		firstGuess = Console.readDouble();
		
		do {
			System.out.print("Enter the desired accuracy: ");
			desiredAccuracy = Console.readDouble();
			if (desiredAccuracy &lt;= 0.0) {
				System.out.println("Accuracy must be greater than 0");
			}
		} while (desiredAccuracy &lt;= 0.0);
		
		System.out.println();
		
		approxRoot = approximateRoot(number, firstGuess, desiredAccuracy);
		actualRoot = Math.sqrt(number);

		System.out.println();		
		System.out.println("Final approximation = " + approxRoot);
		System.out.println("Actual root according to Math.sqrt() = " + actualRoot);
		System.out.println("Error in approximation = " + Math.abs(actualRoot - approxRoot));

	}

	/**
	 * Yield an approximation to the square root of number using the
	 * Newton-Raphson starting with firstGuess as the first approximation,
	 * with an absolute error of less than desiredAccuracy.  Print each
	 * approximation to System.out.
	 */
	static double approximateRoot(double number, double firstGuess, double desiredAccuracy) {
	
		double oldGuess, newGuess = firstGuess;		// the old and new guesses in N-R's method
		System.out.println("Approximation #1: " + newGuess);
	
		int count = 2;	// count of how many approximations are made, starts at 2
		                // because at least 2 are required by N-R's method
		do {
			oldGuess = newGuess;
			newGuess = (oldGuess + number/oldGuess) * .5;
			System.out.println("Approximation #" + count + ": " + newGuess);
			count++;
		} while (Math.abs(newGuess - oldGuess) &gt;= desiredAccuracy);
	
		return newGuess;	
	}

}</pre></body></html>