/* this program uses a formula nextGuess = (lastGuess + n / lastGuess) / 2 repeatedly to approximate the square * root of a number. The main method uses a loop to allow the user to enter positive numbers. A method implements * this formula to estimate the square root. */ import java.util.Scanner; public class Prog6_22 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a positive value and I will approximate its square root "); int value = in.nextInt(); while(value>0) // iterate while the user has positive numbers to test { // we output both the square root as computed by Math.sqrt and our own estimate System.out.printf("%d has a square root of %.2f which I estimated as %.2f\n", value, Math.sqrt(value), mySquareRoot(value)); System.out.print("Enter a positive value and I will approximate its square root "); value = in.nextInt(); } } // method to approximate the square root of an int value, we use two local variales, myLastGuess which is the last // estimate computed, and myNewGuess to compute the new estimate, after each iteration, we replace the old myLastGuess // with the newly computed myGuessGuess public static double mySquareRoot(int x) { double myNewGuess = 1.0, myLastGuess; // myNewGuess can be initialized to anything except 0 do { myLastGuess = myNewGuess; // replace myLastGuess with the previous new guess myNewGuess = (myLastGuess + x / myLastGuess) / 2; // estimate the new guess }while(Math.abs(myNewGuess-myLastGuess)>0.01); // repeat until the two guesses are wtihin .01 together return myNewGuess; } }