Friday, November 16, 2007

ApproximateSqrt

5.22** (Approximating the square root) Implement the sqrt method. The square root of a number, num, can be approximated by repeatedly performing a calculation using the following formula:
nextGuess = (lastGuess + (num / lastGuess)) / 2

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root.

The initial guess will be the starting value of lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of num.
===
ApproximateSqrt.java
===
import javax.swing.JOptionPane;

public class ApproximateSqrt {
public static void main(String[] args) {
String numberToBeSqrtString = JOptionPane.showInputDialog("Please input" +
" number whose square root is to be computed:");
double numberToBeSqrt = Double.parseDouble(numberToBeSqrtString);
double lastGuess = Math.random()*numberToBeSqrt;
double nextGuess = (lastGuess + (numberToBeSqrt / lastGuess)) / 2;
do {
lastGuess = nextGuess;
double placeHolder = (lastGuess + (numberToBeSqrt / lastGuess)) / 2;
nextGuess = placeHolder;
}
while (nextGuess != lastGuess);
System.out.println(nextGuess);
System.out.println(Math.sqrt(numberToBeSqrt));
}
}

No comments: